Express.js连接超时与服务器超时 [英] Express.js connect timeout vs server timeout

查看:258
本文介绍了Express.js连接超时与服务器超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用express和连接超时中间件处理超时.

I am using express and Connect Timeout Middleware to handle the timeouts.

它很好用,但是我默认的node http服务器的超时设置为两分钟.

It works great, but I the default node http server's timeout is set to two minutes.

因此,如果我想将超时中间件设置为大于两分钟的值,我还必须将http服务器超时设置为稍大一些(否则将不调用连接超时处理程序)

Therefore if I want to set my timeout middleware to a value greater than two minutes, I also have to increase the http server timeout to be slightly bigger (otherwise my connect timeout handler is not called)

const app = express();
const http = new Http.Server(app);

http.setTimeout((4 * 60 * 1000) + 1); <-- Must set this

app.use(timeout('4m')); 

如何避免这种情况?我想念什么吗?

How can I avoid this ? Am I missing something ?

推荐答案

如果要使用connect-timeout中间件,则无法避免,因为中间件不会更改套接字超时,默认为2分钟

If you want to use the connect-timeout middleware, you can't avoid it, since the middleware does not change the socket timeout, which defaults to 2 minutes.

使用server.setTimeout()request.setTimeout有两种方法可以避免这种情况.

There are two possible ways to avoid it, either using server.setTimeout() or request.setTimeout.

如果您只想将超时更改为几条路由,而将默认超时保留为其余路由,则建议使用以下方法:request.setTimeout

In case you only want to change the timeout to a few routes, and leave the default timeout to the rest, the recommended approach is to use: request.setTimeout

app.use('/some-routes', (req, res, next) => {
   req.setTimeout((4 * 60 * 1000) + 1);
   next();
}, timeout('4m'));

req.setTimeout设置为大于connect-timeout值的另一种方法是删除connect-timeout中间件并使用其他解决方法,这也不理想.

An alternative to setting the req.setTimeout to a value greater than the connect-timeout value, is dropping the connect-timeout middleware and using another work around, which is also not ideal.

您可以检查此旧的Node.js问题 https://github.com/nodejs/node-v0.x-archive/issues/3460

You can check this old Node.js issue https://github.com/nodejs/node-v0.x-archive/issues/3460

function haltOnTimedout (req, res, next) {
  if (!req.timedout) next()
}

app.use('/some-routes', (req, res, next) => {
    req.setTimeout(4 * 60 * 1000); // No need to offset

    req.socket.removeAllListeners('timeout'); // This is the work around
    req.socket.once('timeout', () => {
        req.timedout = true;
        res.status(504).send('Timeout');
    });

    next();
});


app.use(haltOnTimedout);

// But if the timeout occurs in the middle of a route
// You will need to check if the headers were sent or if the request timedout

app.get('/some-routes', async(req, res, next) => {
  
  // some async processing...
  await asyncOperation();
  
  if (!res.headersSent) // or !req.timedout 
    res.send('done');
 
});

这篇关于Express.js连接超时与服务器超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆