express.js:如何在app.get中使用http.request返回的值
express.js: how to use value returned by http.request in app.get
我想使用app.get从另一个域上的API传递数据。我可以将数据写入控制台,但页面上没有显示任何内容("~/rerestResults")。
这是我迄今为止的代码:
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的结果绑定到变量,并在请求"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
更改为其他内容,因为您需要快递res
,而不是请求res
。
回调是一个异步调用。在收到请求的结果之前,您正在发送响应。
您还需要处理出现错误的情况,否则客户端的请求可能会挂起。
在回调(来自http请求)完成之前,您当前正在发送响应http.request
是异步的,脚本不会等到它完成后再将数据发送回客户端。
您必须等待请求完成,然后将结果发送回客户端(最好是在callback
函数中)。
示例:
http.request(options, function(httpRes) {
// Notice that i renamed the 'res' param due to one with that name existing in the outer scope.
/*do the res.on('data' stuff... and any other code you want...*/
httpRes.on('end', function () {
res.send(content);
});
}).end();
相关文章:
- Angular JS $http request?
- JavaScript 中的 http request in while 循环
- Angular Js Curl -d http request
- 如何使用 javascript for http request 使用 .com url.
- 无法从响应的结束事件中对 Http.Request 进行递归调用
- 如何在 NodeJS 中传递响应参数,包括来自 POST http.request 的正文
- RxJS + Node.js Http Request
- 使用 http.request 会生成错误
- 无法使用 node.js http.request - MapperParsingException[未能解析]将记录插
- 如何使用nodejs连接到代理服务器并通过代理进行http.request
- NodeJS return http.request
- 使用http.request时Nodejs的性能如何扩展
- http.request()s每秒每个node.js进程
- express.js:如何在app.get中使用http.request返回的值
- Node: http.request()行为在发生错误时
- Angular js http request php
- 如何在html中完成SVN的http-request签入/提交
- 节点http.request():与var ClientRequest和callbackFn的关系
- $http request在angular js中被传递给服务器,而不需要在客户端指定它
- Angular2 Http Request