如何修改nodejs请求默认超时时间?

问题描述:

我使用的是 Node/express 服务器.express 的默认超时时间是 120,000 毫秒,但对我来说还不够.当我的响应达到 120,000 毫秒时,控制台将记录 POST/additem 200 120006ms 并且页面显示错误,因此我想将超时设置为更大的值.我该怎么做?

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?

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

I'm assuming you're using express, given the logs you have in your question. The key is to set the timeout property on server (the following sets the timeout to one second, use whatever value you want):

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

如果你不使用 express 而只使用 vanilla node,原理是一样的.以下不会返回数据:

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
');
  }, 200);
}).listen(1337, '127.0.0.1');

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