Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a timeout on a http.request() in Node?

I'm trying to set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this:

var options = { ... } var req = http.request(options, function(res) {   // Usual stuff: on(data), on(end), chunks, etc... }  /* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */ req.socket.setTimeout(myTimeout);   req.socket.on('timeout', function() {   req.abort(); });  req.write('something'); req.end(); 

Any hints?

like image 513
Claudio Avatar asked Jun 02 '11 13:06

Claudio


People also ask

How do I set HTTP request timeout?

Timeouts on http. request() takes a timeout option. Its documentation says: timeout <number> : A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.

What is request timeout in NodeJS?

By default, NodeJS has a timeout value of 120 seconds. Sometimes you may need to increase request timeout in NodeJS to process long running requests.

Does node have a timeout?

In Node. js, default server timeout is 0 milliseconds for the latest version and 2min i.e. (120000 milliseconds) for the older version.

What is the default timeout for HTTP request?

The default value is 60 seconds. If the value of this stanza entry is set to 0 (or not set), connection timeouts between data fragments are governed instead by the client-connect-timeout stanza entry. The exception to this rule occurs for responses returned over HTTP (TCP).


1 Answers

2019 Update

There are various ways to handle this more elegantly now. Please see some other answers on this thread. Tech moves fast so answers can often become out of date fairly quickly. My answer will still work but it's worth looking at alternatives as well.

2012 Answer

Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so:

var options = { ... } var req = http.request(options, function(res) {   // Usual stuff: on(data), on(end), chunks, etc... });  req.on('socket', function (socket) {     socket.setTimeout(myTimeout);       socket.on('timeout', function() {         req.abort();     }); });  req.on('error', function(err) {     if (err.code === "ECONNRESET") {         console.log("Timeout occurs");         //specific error treatment     }     //other error treatment });  req.write('something'); req.end(); 

The 'socket' event is fired when the request is assigned a socket object.

like image 76
Rob Evans Avatar answered Sep 30 '22 14:09

Rob Evans