静态资源服务
要提供静态内容(例如单页应用 SPA),请使用 @nestjs/serve-static 包中的 ServeStaticModule。
安装
首先,安装所需的包:
$ npm install --save @nestjs/serve-static引导启动
安装完成后,把 ServeStaticModule 导入根 AppModule,并向 forRoot() 方法传入一个配置对象来完成配置:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller.js';
import { AppService } from './app.service.js';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'node:path';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(import.meta.dirname, '..', 'client'),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}完成这些之后,构建静态网站,并把它的内容放到 rootPath 属性指定的位置。
配置
ServeStaticModule 接受多种选项来定制其行为。例如,你可以设置渲染静态应用的路径、排除特定路径,或者启用或禁用 Cache-Control 响应头。完整的选项列表见 ServeStaticModuleOptions 接口。
注意
默认情况下,renderPath 匹配所有路径,模块会以 index.html 文件作为响应。这为你的 SPA 启用了客户端路由,而控制器中声明的路由仍由服务端处理。你可以把 serveRoot 和 renderPath 选项与其他选项组合使用,来改变这一行为。使用 Fastify 适配器时,请把 serveStaticOptions.fallthrough 设为 true,以模拟 Express 的 fallthrough 行为,也就是对不存在的路由返回 index.html 而不是 404 错误。
示例
可运行的示例见 GitHub 上的 serve-static 示例。