如何使用sails.js访问外部API? [英] How to access external api using sails.js?
问题描述
我正在尝试使用sails.js从控制器内的facebook访问信息.这是我的代码:
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函数似乎无法正常工作,尝试访问/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)
有人知道我如何使用Sails访问外部API吗?
谢谢
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()
.>
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,
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.
这篇关于如何使用sails.js访问外部API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!