给定一个超时时间为 10 秒的 NodeJS http 服务器:
const httpServer = require('http').createServer(app);
httpServer.timeout = 10 * 1000;
超时时,邮递员会在没有任何响应代码的情况下显示此内容:
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 响应。
根据这个答案,这是预期的行为,套接字只是被破坏了。
在具有 nginx 反向代理的架构中,服务器是否通常只是销毁套接字而不向代理发送超时响应?
你设置,当你设置HTTP服务器超时套接字超时。套接字超时可防止可能想挂断您与 DOS 您的连接的客户端的滥用。它还有其他好处,例如确保一定水平的服务(尽管当您是客户时,这些通常更重要)。
它使用套接字超时而不是发送408
状态代码(请求超时)的原因是因为状态代码可能已经发送成功消息。
如果你想在你的后端实现一个响应超时并优雅地处理它,你可以自己超时响应。请注意,您可能应该用 a408
代替。502
用于像 http 代理 (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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句