nodejs发送http请求接受回来的数据怎么写入页面

2025-04-03 04:56:04
推荐回答(1个)
回答1:

var data="";
router.post(’/report/get’,function(reqs,res){
var urlStr=’http://xxxxxxx/slot/list';//发送的请求地址
var body=reqs.body;//发送的字段{colNum,currentPage}
console.log(“colNum”+JSON.stringify(body));
var contentStr=queryString.stringify(body);
var opt={
“hostname”:url.parse(urlStr).hostname,
“path”:url.parse(urlStr).path,
“method”:“POST”,
“port”:3000,
“headers”:{
.......

var httpModule = urlStr.indexOf(‘https’) === 0 ? https : http;
var req = httpModule.request(opt, function(httpRes) {
var buffers = [];
httpRes.on(‘data’, function(chunk) {
buffers.push(chunk);
});
httpRes.on('end', function(chunk) {
var wholeData = Buffer.concat(buffers);
var dataStr = wholeData.toString('utf8');
console.log('content'+wholeData);
data=wholeData;
//res.send(JSON.stringify(buffers));
});
}).on('error', function(err) {
console.log('error ' + err);
});;
//写入数据,完成发送
req.write(contentStr);
req.end();
res.send(JSON.stringify(data));