我想在單個URL調用中調用多個URL,並將其推送到數組中的json響應,併發送該數組以響應最終用戶。在Node.js中的單個HTTP請求中調用多個HTTP請求
我的代碼看起來像這樣:
var express = require('express');
var main_router = express.Router();
var http = require('http');
urls = [
"http://localhost:3010/alm/build_tool",
"http://localhost:3010/alm/development_tool",
"http://localhost:3010/alm/project_architecture"];
var responses = [];
main_router.route('/')
.get(function (req, res) {
var completed_requests = 0;
for (url in urls) {
http.get(url, function(res) {
responses.push(res.body);
completed_request++;
if (completed_request == urls.length) {
// All download done, process responses array
}
});
}
res.send(responses);
});
我也嘗試過這種使用NPM請求模塊。 當我運行這段代碼時,它只返回NULL或一些只有頭文件的隨機輸出。
我的目標是在單個節點獲取請求中調用多個URL,並將其JSON輸出附加到數組上併發送給最終用戶。
感謝
喲必須使用回調或我可以建議異步模塊https://github.com/caolan/async –
請參閱[這個答案](http://stackoverflow.com/a/26254973/973680)。你實際上應該等待響應的結束,通過使用'res.on('end',function ...' –