How to modify the nodejs request default timeout time?

前端 未结 6 1904
南旧
南旧 2020-11-27 17:05

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

相关标签:
6条回答
  • 2020-11-27 17:23

    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);
    };
    
    0 讨论(0)
  • 2020-11-27 17:24

    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)
    
    0 讨论(0)
  • 2020-11-27 17:33

    Try this:

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

    Refer to request's documentation for other options.

    0 讨论(0)
  • 2020-11-27 17:36

    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);
    });
    
    0 讨论(0)
  • 2020-11-27 17:37

    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;
    

    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/');
    
    0 讨论(0)
  • 2020-11-27 17:40

    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
    
    0 讨论(0)
提交回复
热议问题