我想使用 app.get 从另一个域上的 API 传递数据。我可以将数据写入控制台,但页面上没有显示任何内容(“~/restresults”)。
这是我到目前为止的代码:
app.get('/restresults', function (req, res) {
var theresults;
var http = require('http');
var options = {
port: '80' ,
hostname: 'restsite' ,
path: '/v1/search?format=json&q=%22foobar%22' ,
headers: { 'Authorization': 'Basic abc=='}
} ;
callback = function(res) {
var content;
res.on('data', function (chunk) {
content += chunk;
});
res.on('end', function () {
console.log(content);
theresults = content ;
});
};
http.request(options, callback).end();
res.send(theresults) ;
});
如何将 http.request 的结果绑定(bind)到变量并在请求“restresults/”时返回它?
最佳答案
将 res.send(theresults);
移至此处:
callback = function(res2) {
var content;
res2.on('data', function (chunk) {
content += chunk;
});
res2.on('end', function () {
console.log(content);
theresults = content ;
res.send(theresults) ; // Here
});
};
注意:您必须将 res
更改为其他内容,因为您想要的是 Express res
,而不是请求 res
。
回调是异步调用。您将在收到请求结果之前发送响应。
您还需要处理出现错误的情况,否则客户端的请求可能会挂起。
关于javascript - app.get 中的express.js : how to use value returned by http. 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556779/