Javascript 在 Node.js 中的单个 HTTP 请求中调用多个 HTTP 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34436455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling multiple HTTP requests in a single HTTP request in Node.js
提问by Vaibhav Jain
I am trying to call multiple URL in a single URL call and push it's json response in an array and send that array in response to the end user.
我试图在单个 URL 调用中调用多个 URL,并将它的 json 响应推送到一个数组中,然后将该数组发送给最终用户。
My code look like this:
我的代码如下所示:
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);
});
I have also tried this using npm request module. When i run this code it only return NULL or some random output that have only headers.
我也使用 npm request 模块尝试过这个。当我运行此代码时,它只返回 NULL 或一些只有标题的随机输出。
My aim is to call multiple URL's in a single node get request and append it's JSON output on a array and send to the end user.
我的目标是在单个节点获取请求中调用多个 URL,并将其 JSON 输出附加到一个数组上并发送给最终用户。
Thanks
谢谢
回答by yoogeeks
Here, try this code,
在这里,试试这个代码,
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);
});
Explanation :This code uses asyncand requestnode packages. async.map
by definition takes 3 params, first one being an array, second being the iterator function you want to call with each element of that array, and the callback function, called when async.map has finished processing.
说明:此代码使用异步和请求节点包。async.map
根据定义,需要 3 个参数,第一个是数组,第二个是您要对该数组的每个元素调用的迭代器函数,以及在 async.map 完成处理时调用的回调函数。
map(arr, iterator, [callback])
Produces a new array of values by mapping each value in arr through the iterator function. The iterator is called with an item from arr and a callback for when it has finished processing. Each of these callback takes 2 arguments: an error, and the transformed item from arr. If iterator passes an error to its callback, the main callback (for the map function) is immediately called with the error.
map(arr, iterator, [callback])
通过迭代器函数映射 arr 中的每个值,生成一个新的值数组。使用来自 arr 的项目和完成处理时的回调调用迭代器。这些回调中的每一个都有 2 个参数:一个错误和来自 arr 的转换项。如果迭代器将错误传递给它的回调,则立即调用主回调(对于 map 函数)并带有错误。
Note: All calls to iterator function are parallel.
注意:对迭代器函数的所有调用都是并行的。
Inside your httpGet function, you are calling request
function with passed url, and explicitly telling the response format to be json
. request
, when finished processing, calls the callback function with three params, err - if any, res - server response, body - response body.
In case there is no err
from request
, async.map
collects the results from these callbacks as an array, and passes that array at the end to its third, callback function. Otherwise,if (err) is true, the async.map
function stops the execution and calls its callback with an err
.
在您的 httpGet 函数中,您request
使用传递的 url调用函数,并明确告知响应格式为json
. request
, 处理完成后,调用带有三个参数的回调函数,err - 如果有, res - 服务器响应,body - 响应正文。如果没有err
from request
,async.map
则将这些回调的结果作为数组收集,并在最后将该数组传递给其第三个回调函数。否则,如果 (err) 为真,则async.map
函数停止执行并使用err
.
回答by Ita
I suggest to use the asynclibrary.
我建议使用异步库。
async.map(urls, http.get, function(err, responses){
if (err){
// handle error
}
else {
res.send responses
}
})
The snippet above will perform a http.get
call for each of the urls in parallel, and will call your callback function with the results of all of the calls after all the responses were received.
上面的代码段将http.get
并行执行对每个 url 的调用,并在收到所有响应后使用所有调用的结果调用您的回调函数。
If you want to call the urls in series, you can use async.mapSeries
instead. If you want to limit the number of concurrent requests you can use async.mapLimit
.
如果要连续调用 url,可以async.mapSeries
改用。如果要限制并发请求的数量,可以使用async.mapLimit
.