How to modify the nodejs request default timeout time?

I'm using a Node/express server. The default timeout of express is 120,000 ms, but it is not enough for me. When my response reaches 120,000 ms, the console will log POST /additem 200 120006ms and the page shows an error, so I want to set the timeout to a larger value. How would I do that?

187281 次浏览

Try this:

var options = {
url:  'http://url',
timeout: 120000
}


request(options, function(err, resp, body) {});

Refer to request's documentation for other options.

鉴于你的问题中的日志,我假设你使用的是express。关键是在服务器上设置timeout属性(以下将超时设置为一秒,使用您想要的任何值):

var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;

If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:

var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');


server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');

For specific request one can set timeOut to 0 which is no timeout till we get reply from DB or other server

request.setTimeout(0)

For those having configuration in bin/www, just add the timeout parameter after http server creation.

var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces
*/
server.listen(port);
server.timeout=yourValueInMillisecond

With the latest NodeJS you can experiment with this monkey patch:

const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
const that = this;
socket.setTimeout(this.timeout ? this.timeout : 3000);
socket.on('timeout', function() {
that.abort();
});
originalOnSocket.call(this, socket);
};

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
req.setTimeout(500000);
});