gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:06:09 26 4
gpt4 key购买 nike

我想每次使用不同的主体发出多个 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!')
});

关于node.js - 在nodejs中发送多个具有不同主体的http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com