NodeJS Koa超时时间设置

Koa 框架默认超时时间是 2 minutes。对于一个超过两分钟的请求,Koa框架会自动关闭连接,导致客户端报错:unexpected end of stream on okhttp3.Address。

所以对于超时时间的控制,不仅要设置client的读写超时时间,服务端的超时时间也要考虑。

接下来,讲述如何设置Koa框架的超时时间:

全局设置

let app = new Koa();
let server=app.listen(3000);
server.timeout=5*60*1000;

单个请求设置

router.get("/path",async (ctx)=>{
      ctx.request.socket.setTimeout(5 * 60 * 1000); 
})

如果想要更好的返回值提示,那就参考如下代码:

const createError = require('http-errors');

module.exports = (delay, options={}) => async (ctx, next) => {
    const status  = options.status || 408;
    const message = options.message || 'request time-out';
    const callback = options.callback || function(){};
    let timer; 
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => {
            ctx.state.timeout = true;
            reject(createError(status, message));
            callback(ctx, delay);
        }, delay);
    });
    await Promise.race([timeout, next()]);
    clearTimeout(timer);    
}

具体源码可以查看:

参见:https://github.com/js-fullstack/koa-timeout-v2

1: https://github.com/koajs/koa/issues/766

2: https://stackoverflow.com/questions/40138600/disable-request-timeout-in-koa