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

NestJS默认HTTP请求超时时间是多少?如何配置?

NestJS 默认请求超时与超时配置方案

默认超时时间

NestJS 依赖 Express 或 Fastify 作为底层 HTTP 框架,默认超时规则分两种情况:

  • 基于 Express 时,框架本身没有全局请求超时限制,底层 Node.js http.createServer 也无默认超时,但客户端或反向代理可能自带超时逻辑。
  • 基于 Fastify 时,默认请求超时为 5秒,同时连接超时默认也是5秒。

适配15分钟云函数的配置方法

针对依赖长耗时云函数的场景,需手动调整 NestJS 服务器超时设置:

1. Express 底层配置

在项目入口 main.ts 中直接修改底层 HTTP 服务器的超时:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as http from 'http';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 获取底层服务器,设置超时(15分钟=900000毫秒)
  const server = app.getHttpServer();
  server.setTimeout(900000);
  await app.listen(3000);
}
bootstrap();

2. Fastify 底层配置

创建 Nest 应用时传入 Fastify 适配器的超时参数:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      // 连接超时与请求超时均设为15分钟
      connectionTimeout: 900000,
      requestTimeout: 900000,
    }),
  );
  await app.listen(3000);
}
bootstrap();

3. 路由级自定义超时(可选)

如果仅需给特定云函数相关路由设置超时,可使用拦截器实现:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';

@Injectable()
export class CloudFunctionTimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(900000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(() => new RequestTimeoutException('云函数请求超时,请稍后重试'));
        }
        return throwError(() => err);
      }),
    );
  }
}

注册拦截器:

// 全局注册(所有路由生效)
app.useGlobalInterceptors(new CloudFunctionTimeoutInterceptor());

// 仅给指定控制器/路由生效
@UseInterceptors(CloudFunctionTimeoutInterceptor)
@Controller('cloud-api')
export class CloudApiController {}

官方文档参考位置

NestJS 官方文档的「HTTP 适配器」章节中,分别包含 Express 和 Fastify 的配置说明:

  • Express 适配器:可查看底层服务器配置相关内容
  • Fastify 适配器:可找到 connectionTimeout 和 requestTimeout 参数的详细说明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:30:11