给定一个超时为10秒的NodeJS http服务器:
const httpServer = require('http').createServer(app);
httpServer.timeout = 10 * 1000;在超时时,Postman在没有任何响应代码的情况下显示以下内容:
Error: socket hang up
Warning: This request did not get sent completely and might not have all the required system headers如果NodeJS服务器在nginx反向代理之后,nginx将返回502响应(upstream prematurely closed connection while reading response header from upstream)。但在这里,它只是在本地主机上运行的NodeJS/express。尽管如此,人们仍然希望得到一个适当的http响应。
根据this answer的说法,这是预期的行为,套接字被简单地销毁。
在使用nginx反向代理的架构中,服务器通常只销毁套接字而不向代理发送超时响应吗?
发布于 2020-05-08 07:11:34
您正在设置socket timeout when you're setting the http server timeout。套接字超时防止客户端滥用,这些客户端可能想要挂起您与DOS的连接。它还有其他好处,比如确保一定级别的服务(尽管当您是客户时,这些通常更重要)。
它使用套接字超时而不是发送408状态代码(请求超时)的原因是,可能已经为成功的消息发送了状态代码。
如果你想在你的后台实现响应超时,并优雅地处理它,你可以自己让响应超时。请注意,您可能应该使用408进行响应。502用于像http proxies (nginx)这样的网关指示下行连接失败。
这里有一个简单的稻草人实现来处理这个问题。
const httpServer = require('http').createServer((req, res) => {
setTimeout(()=>{
res.statusCode = 200;
res.statusMessage = "Ok";
res.end("Done"); // I'm never called because the timeout will be called instead;
}, 10000)
});
httpServer.on('request', (req, res) => {
setTimeout(()=>{
res.statusCode = 408;
res.statusMessage = 'Request Timeout';
res.end();
}, 1000)
});
httpServer.listen(8080);https://stackoverflow.com/questions/61668882
复制相似问题