[英]Node.js http.request Express multiple requests with single res.render
[英]Calling multiple HTTP requests in a single HTTP request in Node.js
我試圖在單個URL調用中調用多個URL並在數組中推送它的json響應並發送該數組以響應最終用戶。
我的代碼看起來像這樣:
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輸出附加到陣列上並發送給最終用戶。
謝謝
在這里,試試這個代碼,
const async = require('async');
const request = require('request');
function httpGet(url, callback) {
const options = {
url : url,
json : true
};
request(options,
function(err, res, body) {
callback(err, body);
}
);
}
const urls= [
"http://localhost:3010/alm/build_tool",
"http://localhost:3010/alm/development_tool",
"http://localhost:3010/alm/project_architecture"
];
async.map(urls, httpGet, function (err, res){
if (err) return console.log(err);
console.log(res);
});
說明:此代碼使用async和請求節點包。 根據定義, async.map
需要3個參數,第一個是數組,第二個是要與該數組的每個元素一起調用的迭代器函數,以及當async.map完成處理時調用的回調函數。
map(arr, iterator, [callback])
通過迭代器函數映射arr中的每個值,生成一個新的值數組。 使用arr中的項目和完成處理的回調調用迭代器。 這些回調中的每一個都有兩個參數:一個錯誤,以及來自arr的轉換項。 如果迭代器將錯誤傳遞給其回調,則會立即調用主回調(對於map函數)並顯示錯誤。
注意:對迭代器函數的所有調用都是並行的。
在httpGet函數中,您使用傳遞的url調用request
函數,並明確告知響應格式為json
。 request
,當完成處理時,調用三個參數的回調函數,錯誤 - 如果有的話,res - 服務器響應,正文 - 響應正文。 如果沒有來自request
err
, async.map
這些回調的結果作為數組收集,並將該數組的末尾傳遞給第三個回調函數。 否則,如果(err)為true,則async.map
函數會停止執行並使用err
調用其回調。
我建議使用異步庫。
async.map(urls, http.get, function(err, responses){
if (err){
// handle error
}
else {
res.send responses
}
})
上面的代碼片段將並行執行每個網址的http.get
調用,並在收到所有響應后調用您的回調函數和所有調用的結果。
如果要串行調用URL,可以使用async.mapSeries
。 如果要限制並發請求的數量,可以使用async.mapLimit
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.