gpt4 book ai didi

node.js - 在 Nodejs 中使用 setInterval() 发出 post 请求

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:58 25 4
gpt4 key购买 nike

所以我想每 5 秒调用一次 Web 服务(通过 POST 请求)。但是,当我运行下面的代码时,它只提取一次数据,并且不会再次调用请求。知道出了什么问题吗?

var http = require('http');
var querystring = require('querystring');
var url = require('url')

/*
* web service info
*/
var postData = querystring.stringify({
'index' : '-1',
'status' : '-1',
'format' :'-1',
});


var options = {
host: 'localhost',
path: '/WebApp/WebService.asmx/WebMethod',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};

/*
* Web Service Request Obj
*/
var webServiceReq = http.request(options, function(res) {

res.setEncoding('utf8');

res.on('data', function (chunk) {
console.log('Response: ' + chunk + '\n');
});

});

var getData= function(){
webServiceReq.write(postData);
}

// grab the info every 5 seconds
setInterval(getData, 5000);

最佳答案

两个问题:您永远无法通过调用 end() 来完成请求,并且您试图多次重复使用同一请求对象。您需要将请求对象的创建移至 getData 中,并且需要在调用 write() 之后添加对 end() 的调用。

您可能会找到 Mikeal 的 request库很有用,因为它可以处理这样的细节。

关于node.js - 在 Nodejs 中使用 setInterval() 发出 post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787960/

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