在nodejs中发送具有不同主体的多个http请求

时间:2017-01-25 08:42:31

标签: node.js loops http

我想每次使用循环或类似的东西,使用不同的主体发出多个HTTP请求。目前,我将以下代码用于单个请求,该工作正常:

var http = require('http');

 var post_req  = null,
     post_data = JSON.stringify(require('./resources/example.json'));



 var post_options = {
     hostname: 'example.lk',
     port    : '80',
     path    : '/example',
     method  : 'POST',
     headers : {
         'Content-Type': 'application/json',
         'Authorization': 'Cucmlp1qdq9CfA'
     }
 };

 post_req = http.request(post_options, function (res) {
     console.log('STATUS: ' + res.statusCode);
     console.log('HEADERS: ' + JSON.stringify(res.headers));
     res.setEncoding('utf8');
     res.on('data', function (chunk) {
         console.log('Response: ', chunk);
     });
 });

 post_req.on('error', function(e) {
     console.log('problem with request: ' + e.message);
 });
 post_req.write(post_data);
 post_req.end();

如何使用此代码预先形成多个来电?

1 个答案:

答案 0 :(得分:1)

您可以使用async来调用多个`http

var async = require('async');
var http = require('http');

var post_data = [ data1, data2, data2]; //array of data, you want to post

//asynchronously, loop over array of data, you want to push
async.each(post_data, function(data, callback){

  var post_options = {
    hostname: 'example.lk',
    port    : '80',
    path    : '/example',
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json',
        'Authorization': 'Cucmlp1qdq9CfA'
    }
  };

  post_req = http.request(post_options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ', chunk);
    });
    res.on('end', function () {
        callback();
    });
  });

  post_req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
  });
  post_req.write(data); //posting data
  post_req.end();
}, function(err){
  console.log('All requests done!')
});