express.js:如何在app.get中使用http.request返回的值

express.js: how to use value returned by http.request in app.get

本文关键字:http request 返回 get js app express      更新时间:2023-09-26

我想使用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();