How can I retry connecting multiple times while making an http request in node.js if the server is not responding?
If the server is not responding, how can I reconnect? I am getting an error ECONNREFUSED
, but I want to reconnect at least 5 times.
Here is my code:
var body = JSON.stringify(saveObj);
var request = http.request({
host: BASE_URL,
port: PORT,
path: LINK_SAVE,
url : 'https://coherent-bay-777.appspot.com/_ah/api/timesOfIndia/v1/addChannel',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body)
}
}, function(res) {
var resp = '';
res.on('data', function(data) {
resp += data;
});
res.on('end', function() {
resp = JSON.parse(resp);
if(resp.id) {
winston.info(resp.id);
saveObj.update({$set : { id : resp.id }},
function(err) {
if(err) {
winston.error(err);
} else {
cb();
}
});
} else {
cb();
}
});
res.on('error', function(err) {
winston.error(err);
//cb();
});
winston.info('Request Ended');
});
if(body == '{}') {
cb();
return;
}
request.on('socket', function (socket) {
socket.setTimeout(15000);
socket.on('timeout', function() {
console.log("Timeout, aborting request")
request.abort();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
error callback will receive a "socket hang up" on timeout
});
request.write(body);
request.end();
+3
source to share
No one has answered this question yet
Check out similar questions: