victormejia
victormejia

Reputation: 1184

Making a post request with setInterval() in Nodejs

So I want to call a web service (through POST request) every 5 seconds. However, when I run the code below, it only pulls the data once, and doesn't call the request again. Any idea what is wrong?

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);

Upvotes: 1

Views: 2169

Answers (1)

ebohlman
ebohlman

Reputation: 15003

Two problems: you're never completing your request by calling end() on it, and you're trying to re-use the same request object multiple times. You need to move the creation of the request object into getData and you need to add a call to end() after the call to write().

You might find mikeal's request library useful, as it takes care of details like this.

Upvotes: 2

Related Questions