You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TypeScript中设置Node.js HTTP Server的requestTimeout问题

解决Node.js 18 + TypeScript下HTTP服务器requestTimeout设置问题

问题背景

我们将Node版本升级至18.4后,发现Node 18的HTTP服务器默认启用了5分钟请求超时,导致应用中部分慢端点失效。项目基于TypeScript,创建服务器的代码如下:

import * as express from 'express';
import * as http from 'http';

this.app = express();
// 其他配置
const server = http.createServer(this.app);

尝试两种方式设置超时均失败:

  1. 直接赋值requestTimeout触发TypeScript编译错误:
server.requestTimeout = 9000000; // 自定义超时时间

TSError: ⨯ Unable to compile TypeScript:
server/init.ts:232:12 - error TS2339: Property 'requestTimeout' does not exist on type 'Server'.

  1. 使用setTimeout方法,但实际并未延长请求超时:
server.setTimeout(9000000);

但在调试器控制台手动执行server.requestTimeout = 9000000却能正常生效。


解决方案

1. 升级@types/node类型包(推荐)

TypeScript编译报错的核心原因是当前安装的@types/node版本过低,未包含Node.js 18新增的requestTimeout属性定义。执行以下命令升级到对应版本:

npm install @types/node@^18 --save-dev
# 或使用yarn
yarn add @types/node@^18 --dev

升级完成后,直接使用server.requestTimeout = 9000000;即可正常编译并生效。

2. 临时类型断言(不推荐长期使用)

如果暂时无法升级类型包,可以通过类型断言绕过TypeScript的类型检查:

// 简单粗暴的any断言
(server as any).requestTimeout = 9000000;

// 更精确的类型定义(可选)
interface ServerWithRequestTimeout extends http.Server {
  requestTimeout: number;
}
(server as ServerWithRequestTimeout).requestTimeout = 9000000;

3. 注意区分requestTimeout与setTimeout的差异

server.setTimeout()设置的是socket连接的空闲超时时间,而非Node.js 18新增的请求处理超时时间,这就是为什么调用setTimeout无法解决慢端点超时问题的原因。两者是完全不同的配置项。


内容的提问来源于stack exchange,提问作者Mario Stoilov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:01:24