简体   繁体   English

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

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

I want to use app.get to deliver the data from an API on another domain. 我想使用app.get从另一个域上的API传递数据。 I can write the data to the console, but nothing is appearing on the page ('~/restresults'). 我可以将数据写入控制台,但是页面上什么都没有显示(“〜/ restresults”)。

This is the code I have so far: 这是我到目前为止的代码:

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) ; 

});

how can I bind the result of the http.request to a variable and return it when 'restresults/' is requested? 如何将http.request的结果绑定到变量并在请求“ restresults /”时将其返回?

Move res.send(theresults); 移动res.send(theresults); to here: 到这里:

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
  });
};

Note: You'll have to change res to something else as you want the express res , no the request res . 注意:您需要将res更改为其他内容,因为您需要express res ,而无需request res

The callback is an asynchronous call. 回调是一个异步调用。 You're sending the response before you get a result from the request. 您要先发送响应,然后才能从请求中获取结果。

You'll also want to handle the case in which there is an error, otherwise the client's request may hang. 您还需要处理出现错误的情况,否则客户端的请求可能会挂起。

You are currently sending the response before the callback (from the http request) is done. 当前(在http请求中)回调完成之前,您正在发送响应。
The http.request is async, the script will not wait til its done and then send the data back to client. http.request是异步的,脚本不会等待直到完成,然后将数据发送回客户端。

You will have to wait for the request to be done and then send the result back to the client (preferably in the callback function). 您将必须等待请求完成,然后将结果发送回客户端(最好在callback函数中)。

Example : 范例

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM