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

我正在使用一个节点/快递服务器。 express的默认超时时间是120,000ms,但对我来说还不够。 当我的响应达到120,000毫秒时,控制台将loggingPOST /additem 200 120006ms ,页面显示错误,所以我想将超时设置为更大的值。 我该怎么做?

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

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

如果你不使用快递,只与香草节点工作,原则是一样的。 以下将不会返回数据:

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

尝试这个:

 var options = { url: 'http://url', timeout: 120000 } request(options, function(err, resp, body) {}); 

有关其他选项,请参阅请求的文档。

对于在bin/www中configuration的用户,只需在http服务器创build后添加timeout参数即可。

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

对于特定的请求,可以将timeOut设置为0,这是不超时,直到我们从DB或其他服务器得到答复

 request.setTimeout(0)