且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在node.js http模块中超时时发送响应

更新时间:2022-05-31 05:41:26

文档确实是正确的,但是看起来http模块添加了一个调用socket.destroy()的超时"侦听器.因此,您需要做的是通过调用request.socket.removeAllListeners('timeout')摆脱该侦听器. 因此您的代码应如下所示:

The documentation is indeed correct, however it looks like the http module adds a 'timeout' listener which calls socket.destroy(). So what you need to do is get rid of that listener by calling request.socket.removeAllListeners('timeout'). So your code should look like:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.removeAllListeners('timeout'); 
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);