1

所以我想每 5 秒调用一次网络服务(通过 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);
4

1 回答 1

2

两个问题:你永远不会通过调用end()它来完成你的请求,并且你试图多次重用同一个请求对象。您需要将请求对象的创建移入getData,并且需要end()在调用write().

您可能会发现 mikeal 的请求库很有用,因为它处理了这样的细节。

于 2012-08-03T03:31:05.317 回答