2013-08-26 68 views
3

我想使用sails.js訪問控制器內的facebook信息。這裏是我的代碼:如何使用sails.js訪問外部API?

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'); 
    }); 



    }); 
    } 

}; 

的http.request功能看起來不工作,雖然並試圖訪問時,我得到一個錯誤/頂/ 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) 

有誰知道如何使用sails訪問外部API?

感謝,

回答

4

host不應該包括協議:

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

如果你想使用https,使用https模塊,而不是http,並使用端口443和不當您完成請求時忘記添加req.end()

+0

謝謝!它工作完美! – adc06