2017-01-25 8 views
1

ループなどを使用して、毎回異なるボディで複数のHTTPリクエストを作成したいと考えています。現在、私は正常に動作し、単一の要求のために以下のコードを使用します。nodejsに異なるボディを持つ複数の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(); 

は、どのように私は複数の呼び出しをプリフォームするために、このコードを使用することができますか?

答えて

0

あなたは魅力のようないくつかの `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!') 
}); 
+0

作品を呼び出すためにasyncを使用することができます!感謝のブラジャー – frodo

関連する問題