node.js - Express.js 连接超时与服务器超时

标签 node.js express connection-timeout

我正在使用 express 和 Connect Timeout Middleware处理超时。

它工作得很好,但我将默认的 node http 服务器的超时设置为两分钟。

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

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

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

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

如何避免这种情况?我错过了什么吗?

最佳答案

如果你想使用connect-timeout中间件,你无法避免它,因为中间件不会改变套接字超时,默认为2分钟。

有两种可能的方法可以避免它,使用server.setTimeout()request.setTimeout

如果您只想更改少数路由的超时,而将默认超时保留给其余路由,建议的方法是使用:request.setTimeout

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

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

您可以检查这个旧的 Node.js 问题 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');
 
});

关于node.js - Express.js 连接超时与服务器超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364401/

相关文章:

node.js - grunt-contrib-copy 因不允许 EPERM 操作而死亡 "C:\Documents and Settings"

javascript - Node.js Express 应用程序无法从 dropzone.js 回调重定向

php - "failed to open stream: Connection timed out"即使远程站点已启动并正在运行

spring-mvc - C3P0 连接池使用此配置给出连接超时错误

java - 如何测试 JAX-WS 连接超时

node.js - 如何轻松验证安装的 npm 依赖项是否正确?

node.js - 如何使用 Handlebars 在 KeystoneJS 中指定模板?

javascript - 异步功能不起作用

javascript - NodeJS MongoDB 动态查询

javascript - MongoDB:使用过滤器获取附近的所有内容