2014-08-28 33 views
0

我想使用app.get从另一个域上的API传递数据。我可以将数据写入控制台,但没有任何内容出现在页面上('〜/ restresults')。express.js:如何使用app.get中的http.request返回的值

这是我到目前为止的代码:

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 /”要求?

回答

2

移动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

该回调是一个异步调用。在收到请求的结果之前,您正在发送回复。

您还需要处理发生错误的情况,否则客户端的请求可能会挂起。

2

您正在发送响应(来自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(); 
相关问题