简体   繁体   English

在Node.js中的单个HTTP请求中调用多个HTTP请求

[英]Calling multiple HTTP requests in a single HTTP request in Node.js

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. 我也尝试使用npm请求模块。 When i run this code it only return NULL or some random output that have only headers. 当我运行此代码时,它只返回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 谢谢

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 async and request node packages. 说明:此代码使用async请求节点包。 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. 通过迭代器函数映射arr中的每个值,生成一个新的值数组。 The iterator is called with an item from arr and a callback for when it has finished processing. 使用arr中的项目和完成处理的回调调用迭代器。 Each of these callback takes 2 arguments: an error, and the transformed item from arr. 这些回调中的每一个都有两个参数:一个错误,以及来自arr的转换项。 If iterator passes an error to its callback, the main callback (for the map function) is immediately called with the error. 如果迭代器将错误传递给其回调,则会立即调用主回调(对于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 . 在httpGet函数中,您使用传递的url调用request函数,并明确告知响应格式为json request , when finished processing, calls the callback function with three params, err - if any, res - server response, body - response body. request ,当完成处理时,调用三个参数的回调函数,错误 - 如果有的话,res - 服务器响应,正文 - 响应正文。 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. 如果没有来自request errasync.map这些回调的结果作为数组收集,并将该数组的末尾传递给第三个回调函数。 Otherwise,if (err) is true, the async.map function stops the execution and calls its callback with an err . 否则,如果(err)为true,则async.map函数会停止执行并使用err调用其回调。

I suggest to use the async library. 我建议使用异步库。

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调用,并在收到所有响应后调用您的回调函数和所有调用的结果。

If you want to call the urls in series, you can use async.mapSeries instead. 如果要串行调用URL,可以使用async.mapSeries If you want to limit the number of concurrent requests you can use async.mapLimit . 如果要限制并发请求的数量,可以使用async.mapLimit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM