How to access external api using sails.js?

爱⌒轻易说出口 提交于 2019-12-09 13:32:34

问题


I am trying to access information from facebook within a controller using sails.js. Here is my code:

module.exports = {


  commonLikes : function(req,res){
    var other_uid = req.param('uid');
    //var me = req.params.user.uid;
    console.log(other_uid);

    User.findOne({uid : other_uid}).done( function(err,data){
        var other = data;

    var http = require('http'), options = {
            host : "https://graph.facebook.com",
            port : 80,
            path : "/"+other.uid+"/likes?access_token="+other.token,
            method : 'GET'
    };

    var webservice_data = "";

    var webservice_request = http.request(options, function(webservice_response)
    {
        webservice_response.on('error', function(e){ console.log(e.message); });
        webservice_response.on('data', function(chunk){ webservice_data += chunk;});
        webservice_response.on('end', function(){res.send(webservice_data);});
        console.log('coucou');
    });



    });
  }

};

The http.request function doesn't look to work though and I get an error when trying to access /Likes/commonLikes?uid=XXXXX.

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

Does anyone knows how I can access an external API using sails?

Thanks,


回答1:


The host shouldn't include the protocol:

    var http = require('http'), options = {
        host : "graph.facebook.com",
        port : 80,
        path : "/"+other.uid+"/likes?access_token="+other.token,
        method : 'GET'
    };

If you want to use https, use the https module instead of http, and use port 443. And don't forget to add req.end() when you're done with the request.



来源:https://stackoverflow.com/questions/18451158/how-to-access-external-api-using-sails-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!