首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么NodeJS http服务器在超时时关闭套接字而没有响应?

为什么NodeJS http服务器在超时时关闭套接字而没有响应?
EN

Stack Overflow用户
提问于 2020-05-08 06:31:54
回答 1查看 593关注 0票数 0

给定一个超时为10秒的NodeJS http服务器:

代码语言:javascript
复制
const httpServer = require('http').createServer(app);
httpServer.timeout = 10 * 1000;

在超时时,Postman在没有任何响应代码的情况下显示以下内容:

代码语言:javascript
复制
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反向代理的架构中,服务器通常只销毁套接字而不向代理发送超时响应吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-08 07:11:34

您正在设置socket timeout when you're setting the http server timeout。套接字超时防止客户端滥用,这些客户端可能想要挂起您与DOS的连接。它还有其他好处,比如确保一定级别的服务(尽管当您是客户时,这些通常更重要)。

它使用套接字超时而不是发送408状态代码(请求超时)的原因是,可能已经为成功的消息发送了状态代码。

如果你想在你的后台实现响应超时,并优雅地处理它,你可以自己让响应超时。请注意,您可能应该使用408进行响应。502用于像http proxies (nginx)这样的网关指示下行连接失败。

这里有一个简单的稻草人实现来处理这个问题。

代码语言:javascript
复制
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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61668882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档