您好,我在 Nodejs 中设置了一个 REST API,并且 ajax 调用工作正常,直到我尝试从该方法内调用外部 REST 服务。
任何人都可以帮我解决为什么这不起作用吗?我使用 Nodejs 和 Express 在端口 3000 上运行,目前基本上是 localhost。咆哮我的工作正在进行中,但它已经改变了很多。我之前使用的是 request 模块,但现在又回到了 http。
app.get('/api/exchange', function (req, res){
var text = '';
var options = {
host : 'rate-exchange.appspot.com',
port : 3000,
path : '/currency?from=GBP&to=USD',
method : 'GET'
};
var call = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
text = "made it in";
res.on('data', function(d) {
text = "here";
});
});
call.end();
call.on('error', function(e) {
text = "error";
});
res.json({ msg: text });
});
请原谅我的经典 javascript 调试技术
,我基本上只是使用 text
来查看它的走向。
当我运行这个时,我得到以下结果。
{
"msg": ""
}
附:任何人都知道任何好的 Node 调试工具,我将不胜感激。
最佳答案
我猜port:3000
是错误的。您应该从 http.request
回调函数中获得响应。
app.get('/', function (req, res){
var text = '';
var options = {
host : 'rate-exchange.appspot.com',
//port : 3000,
path : '/currency?from=GBP&to=USD',
method : 'GET'
};
var call = http.request(options, function(resp) {
console.log("statusCode: ", res.statusCode);
text = "made it in";
resp.on('data', function(d) {
text = "here";
console.log("response data: "+d);
});
});
call.end();
call.on('error', function(e) {
text = "error";
});
//res.json({ msg: text });
});
关于javascript - 客户端调用的 api 方法内的 HTTP GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18433257/