Skip to content

NestJS 统一 API 前缀

在应用入口调用 app.setGlobalPrefix(),可以为全部 HTTP 路由添加统一前缀。

ts
import { NestFactory } from '@nestjs/core'

import { AppModule } from './app.module'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  app.setGlobalPrefix('api')

  await app.listen(3000)
}

void bootstrap()

假设 Controller 保持原有路由定义:

ts
import { Controller, Get, Param } from '@nestjs/common'

@Controller('users')
export class UsersController {
  @Get()
  findAll() {}

  @Get(':id')
  findOne(@Param('id') id: string) {}
}

应用启动后,接口地址为:

  • GET http://localhost:3000/api/users
  • GET http://localhost:3000/api/users/:id

全局前缀只需在 main.ts 注册一次,不需要在每个 Controller 中重复写 api。Controller 中的 @Controller('users') 与方法路由仍只描述业务路径。

排除路由

健康检查等不希望带前缀的路由可通过 exclude 排除:

ts
import { RequestMethod } from '@nestjs/common'

app.setGlobalPrefix('api', {
  exclude: [{ path: 'health', method: RequestMethod.GET }],
})

此时 GET /health 不带前缀,其他路由仍使用 /api

参考

基于 MIT 许可发布