NestJS中文文档
HTTP / HTTP 适配器
已译 191/191

HTTP 适配器

Nest 不直接与 HTTP 服务器交互。它通过一个 HTTP 适配器(HTTP adapter)来完成,适配器的主要工作是把中间件和处理器代理到相应的库特有实现。这让 Nest 与框架无关:你的控制器、提供者、守卫、管道和过滤器在下文每个适配器上都能原样运行,你也可以从一个适配器迁移到另一个。

适配器 包 基于
ExpressAdapter @nestjs/platform-express Express(默认)
FastifyAdapter @nestjs/platform-fastify Fastify
NodeAdapter @nestjs/platform-node Node.js 的 node:http 模块
提示

框架适配器只能为提供类似 Express 的请求/响应管线处理的库实现。

选择适配器

从 NestJS v12.3 开始,我们推荐 NodeAdapter。它是三者中最快的(见性能),并且它的请求与响应对象自带 Express 风格的辅助方法,因此大多数 Express 中间件、以及为 Express 适配器编写的大多数代码都能原样使用。不传适配器时 Nest 仍使用 Express,因此你需要主动选用,见 Node 适配器。在 NestJS v13 中,NodeAdapter 将成为默认。

如果要使用 Fastify 插件和路由约束等特性,请选择 FastifyAdapter。如果你的应用依赖 Node 适配器未实现的 Express API(见 Express 兼容性),或依赖只支持 Express 的包,请继续使用 ExpressAdapter。

性能

在我们的基准测试中(wrk、100 个连接、Node.js 24,分别针对一个普通 GET 路由、一个带参数的 GET 路由和一个带 JSON 体的 POST 路由),Nest 在 NodeAdapter 上每秒处理的请求数比 ExpressAdapter 多约 50%,比 FastifyAdapter 多约 5%。要在你自己的机器上跑同样的基准,请按 nestjs/nest#18063 中的步骤操作。

请记住,适配器只处理每个请求的一小部分。查询数据库或调用其他服务的路由大部分时间都在等它们,因此适配器的选择对高请求率下的轻量路由影响最大。

如果想看切换适配器在你自己的应用中(而不是基准中)带来了什么变化,请把这次切换作为独立发布上线,并安装 NestJS Observe。Observe 在三个适配器上以相同方式记录请求,每次发布都会得到一个判定,对比该发布前后各路由的延迟与错误率,因此变快的轻量路由和毫无变化的重路由都会体现出来(见发布及其判定)。

Node 适配器

NodeAdapter 让 Nest 直接运行在 node:http 模块上,中间没有其他框架。先安装所需的包:

$ npm i --save @nestjs/platform-node

然后把 NodeAdapter 实例传给 NestFactory.create():

main.ts
import { NestFactory } from '@nestjs/core';
import { NestNodeApplication, NodeAdapter } from '@nestjs/platform-node';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create<NestNodeApplication>(
    AppModule,
    new NodeAdapter(),
  );
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();

NestNodeApplication 类型为你提供应用对象的平台特有方法:useBodyParser()、useStaticAssets()、setViewEngine()、setBaseViewsDir()、setLocal() 和 inject()。

在端到端测试中也要把 NodeAdapter 实例传给 createNestApplication()。不传的话,测试模块会创建 Express 应用,测试就不在你应用实际使用的适配器上运行;而且如果未安装 @nestjs/platform-express 包,测试会失败:

app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());

与 Fastify 适配器一样,app.inject() 用 light-my-request 向应用发送伪造请求,因此测试不需要监听中的服务器,只需 app.init():

const result = await app.inject({ method: 'GET', url: '/cats' });
expect(result.statusCode).toEqual(200);

Express 兼容性

请求与响应是 NodeRequest 和 NodeResponse 的实例(从 @nestjs/platform-node 导出)。它们在 Node 的 IncomingMessage 和 ServerResponse 之上补齐了中间件、异常过滤器和 @Res() 处理器通常依赖的 Express 风格属性与方法,例如 req.get()、req.is()、req.route、req.ip、req.ips、req.hostname、res.status()、res.send()、res.json()、res.set()、res.type()、res.cookie()、res.redirect()、res.sendFile() 和 res.locals。中间件在 Express 风格的栈中运行,并使用同样的 (req, res, next) 签名。

流行的 Express 中间件包(如 helmet、compression、cookie-parser、express-session、express-rate-limit、csrf-csrf、morgan 和 passport,以及 @nestjs/passport 的守卫)都可像在 Express 适配器上那样工作。当本文档某章分别为 Express 和 Fastify 给出说明时(例如压缩或 Session),请按 Express 的那份操作。

Node 适配器有意在几处与 Express 不同:

  • 路由按具体程度匹配(与 Fastify 相同),而不是按注册顺序。
  • 路径匹配区分大小写,路由、中间件和 exclude() 皆然,与 Fastify 相同。
  • 路由处理器返回的字符串以 text/plain 发送,而不是 text/html。
  • req.path 是路由器匹配到的解码后路径,因此检查它的中间件看到的路径与路由一致。
  • 适配器不添加 ETag 头,条件请求(If-None-Match、If-Modified-Since)会得到完整响应而不是 304 Not Modified(与 Fastify 相同),即使处理器自己设置了 ETag 或 Last-Modified。res.sendFile() 和 useStaticAssets() 仍会发送 ETag 并以 304 应答。
  • 超过 100 个字符的路由参数不会匹配(见 Node 适配器选项)。
  • 含 __proto__ 或 constructor.prototype 键的 JSON 体会被拒绝(见请求体解析器)。

有些不支持 Express API:res.render()(请改用 @Render() 装饰器)、res.download()、res.format()、res.attachment()、res.contentType()(请改用 res.type())、res.jsonp()、res.links()、res.location()(请改用 res.set('Location', url))、res.vary()、req.accepts() 及其变体、req.fresh 与 req.stale、req.host、req.range()、req.subdomains、req.xhr、用 app.use() 挂载 Express 应用,以及 Express 设置——后者改用适配器的选项(例如 trust proxy 设置对应 trustProxy)。

Node 适配器选项

与 Fastify 一样,路由参数上限为 100 个字符。参数更长的请求会落到另一个匹配的路由(如果有,例如通配符路由),否则得到 414 URI Too Long 响应。要改变该限制,请把 maxParamLength 选项传给 NodeAdapter 构造函数:

new NodeAdapter({ maxParamLength: 500 });

在反向代理或负载均衡器之后,连接来自代理,因此 req.ip 是代理的地址;当代理终止 TLS 时,req.protocol 是 'http'。要从受信任代理设置的 X-Forwarded-For、X-Forwarded-Proto 和 X-Forwarded-Host 头中读取客户端地址、协议和主机,请传 trustProxy 选项。与 Fastify 一样,它可以取 true(信任所有代理)、你的代理地址或子网(如 'loopback' 或 '10.0.0.0/8',可用逗号分隔或数组传入),或一个接收地址与跳数并返回是否信任的函数:

new NodeAdapter({ trustProxy: 'loopback' });

此后 req.ip、req.ips、req.protocol、req.secure 和 req.hostname 的行为与 Express 一致,子域路由同样如此。与 Express 的设置不同,该选项不接受跳数:与 Fastify 一样,传数字表示不信任任何代理,因为它无法区分代理和自行发送 X-Forwarded-For 头的客户端。

警告

只信任位于应用前方的代理。能直连应用的客户端可以发送任意 X-Forwarded-* 头。

默认情况下,查询串被解析为扁平键,与 Express 和 Fastify 一致:?filter[where][name]=John 会得到 filter[where][name] 键。要解析嵌套对象与数组,请传 querystringParser 选项,与 Fastify 一样。它接收查询串(不含前导 ?,URL 中没有查询串时为空字符串):

import qs from 'qs';

new NodeAdapter({ querystringParser: (str) => qs.parse(str) });

请求体解析器

Node 适配器自带 json、urlencoded、text 和 raw 请求体解析器,因此不依赖 body-parser 包。它们接受与 body-parser 对应实现相同的选项,例如 limit、inflate、strict 和 type。与 Express 一样,Nest 默认注册 json 和 urlencoded 解析器,rawBody 选项和 useBodyParser() 方法的用法与原始请求体中所述一致。

默认请求体大小限制是 100kb(与 Express 相同),而 Fastify 适配器继承 Fastify 的 1 MiB 默认值。更大的体会被拒绝,返回 413 Payload Too Large。要提高限制,见请求体解析器大小限制。

与 Fastify 一样,json 解析器会拒绝试图注入原型属性的请求体:含 __proto__ 或 constructor.prototype 键的体会得到 400 Bad Request 响应。若要改为丢弃这些键,或保留它们(body-parser 的行为),请把 onProtoPoisoning 和 onConstructorPoisoning 选项设为 'remove' 或 'ignore'。urlencoded 解析器接受相同选项。

app.useBodyParser('json', { onProtoPoisoning: 'remove' });

服务器超时

与 Express 一样,适配器保留 Node http.Server 的默认值:空闲的 keep-alive 连接在 5 秒后关闭(keepAliveTimeout),请求必须在 300 秒内完整到达(requestTimeout)。Fastify 把这两项分别设为 72 秒和不限。在负载均衡器或反向代理之后,请让 keepAliveTimeout 长于代理的空闲超时,否则代理可能复用服务器正在关闭的连接,从而返回 502 Bad Gateway。请在调用 listen() 之前设置服务器的超时:

const server = app.getHttpServer();
server.keepAliveTimeout = 72_000;

静态资源与视图

useStaticAssets() 用 serve-static 包提供某个目录。它接受该包的选项,另加一个 prefix,与 Express 相同。setViewEngine() 既接受引擎名称(与 Express 相同,见模型-视图-控制器),也接受 @fastify/view 的选项对象(含引擎与 templates 目录)。

其他包

  • 文件上传: 从 @nestjs/platform-node 而不是 @nestjs/platform-express 导入 FileInterceptor()、其他上传拦截器和 MulterModule。它们是同一套基于 Multer 的拦截器,因此文件上传一章的其余内容原样适用。
  • 提供单页应用: @nestjs/serve-static 包(v12.1.1 或更高)通过适配器提供文件,因此不需要 express 包。其面向客户端路径的回退路由需要 @nestjs/platform-node v12.3.1 或更高。
  • GraphQL: 使用 @nestjs/apollo 驱动(v14.1.1 或更高),与 Express 相同。@nestjs/mercurius 驱动需要 Fastify 适配器。

Fastify 适配器

Fastify 是 Nest 的一个很好的替代框架,因为它以类似 Express 的方式解决设计问题。它自带插件生态。要使用 Fastify,请选择内置的 FastifyAdapter,如下所示。

安装

先安装所需的包:

$ npm i --save @nestjs/platform-fastify

适配器

安装 Fastify 平台后,就可以使用 FastifyAdapter。

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

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();

默认情况下,Fastify 只监听 localhost 接口(见 Fastify 快速开始指南)。要接受其他主机上的连接,请在 listen() 调用中指定 '0.0.0.0':

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  await app.listen(3000, '0.0.0.0');
}

平台特有的包

使用 FastifyAdapter 时,Nest 把 Fastify 作为 HTTP 提供者。这意味着依赖 Express 的配方可能无法工作,请改用与 Fastify 等价的包。

重定向响应

Fastify 处理重定向响应的方式与 Express 略有不同。要用 Fastify 重定向,请先用 status() 设置状态码,再用 URL 调用 redirect():

@Get()
index(@Res() res) {
  res.status(302).redirect('/login');
}

Fastify 选项

你可以通过 FastifyAdapter 构造函数把选项传给 Fastify 实例。例如:

new FastifyAdapter({ logger: true });

中间件

中间件函数收到的是原始 req 和 res 对象,而不是 Fastify 的包装对象。这是 Nest 底层使用的 @fastify/middie 包的工作方式。更多信息见 Fastify 中间件文档。

logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { FastifyRequest, FastifyReply } from 'fastify';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
    console.log('Request...');
    next();
  }
}
import { Injectable } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware {
  use(req, res, next) {
    console.log('Request...');
    next();
  }
}

这与 Express 有几处差异,在迁移中间件时很重要:

  • 原始 res 没有 res.status() 或 res.json() 这类 Express 辅助方法,调用它们会抛 TypeError,请求以 500 响应失败。要拒绝请求,请抛出异常(例如 throw new UnauthorizedException()),异常层会把它转成相应的响应。
  • 中间件在 Fastify 解析请求体之前运行,且原始 req 不携带路由参数,因此其中的 req.body 和 req.params 都是 undefined。依赖它们的检查(例如校验签名体)应放在守卫中,守卫在两者都可用之后运行。
提示

守卫、拦截器和异常过滤器从 switchToHttp() 拿到的是 Fastify 的 FastifyRequest 和 FastifyReply 包装对象,而不是中间件收到的原始对象。在那里请使用 reply.status() 和 reply.send(),或 reply.raw 取底层 Node.js 响应。

路由配置

使用 @RouteConfig() 装饰器应用 Fastify 的路由配置特性。

@RouteConfig({ output: 'hello world' })
@Get()
index(@Req() req) {
  return req.routeConfig.output;
}

路由约束

使用 @RouteConstraints() 装饰器应用 Fastify 的路由约束特性。

@RouteConstraints({ version: '1.2.x' })
newFeature() {
  return 'This works only for version >= 1.2.x';
}
提示

@RouteConfig() 和 @RouteConstraints() 从 @nestjs/platform-fastify 导入。

示例

可运行的示例见 nestjs/nest 仓库。

Express 适配器

Express 使用广泛、众所周知,并有大量兼容中间件。当你不给 NestFactory.create() 传适配器时,Nest 使用 @nestjs/platform-express 包的 ExpressAdapter,因此无需任何配置。要访问应用对象的 Express 特有方法,请传入 NestExpressApplication 类型:

const app = await NestFactory.create<NestExpressApplication>(AppModule);

若要在 NodeAdapter 成为默认之后仍让应用留在 Express 上,请显式传入 ExpressAdapter 实例:

main.ts
import { NestFactory } from '@nestjs/core';
import {
  ExpressAdapter,
  NestExpressApplication,
} from '@nestjs/platform-express';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(),
  );
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();