[英]send multiple http requests with different body in 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();
如何使用此代码执行多个呼叫?
您可以使用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!')
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.