2014-08-28 34 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(); 
相關問題