1

I want to make multiple HTTP requests with different bodies each time, using loop or something similar. Currently I use the following code for a single request which works fine:

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();

How can I use this code to preform multiple calls?

1 Answer 1

2

You can use async to call several `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!')
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.