主题
路由前缀
NestJS 的 HTTP 路由可以由全局路由前缀、Controller 路由前缀和路由方法路径共同组成。
全局路由前缀
在应用入口调用 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('v1')
await app.listen(3000)
}
void bootstrap()全局路由前缀只需在 main.ts 注册一次,不需要在每个 Controller 中重复声明 v1。
排除指定路由
健康检查等不需要全局前缀的路由,可以通过 exclude 排除:
ts
import { RequestMethod } from '@nestjs/common'
app.setGlobalPrefix('v1', {
exclude: [{ path: 'health', method: RequestMethod.GET }],
})此时 GET /health 不使用全局前缀,其他路由仍以 /v1 开头。
Controller 路由前缀
@Controller() 可以为当前 Controller 中的所有路由声明前缀,用于组织同一业务资源下的端点:
ts
import { Controller, Get, Param } from '@nestjs/common'
@Controller('users')
export class UsersController {
@Get()
findAll() {}
@Get(':id')
findOne(@Param('id') id: string) {}
}@Controller('users') 只描述当前 Controller 的业务路径,不需要包含全局路由前缀。
路径组合规则
最终路由由以下三部分依次组合:
md
全局路由前缀 + Controller 路由前缀 + 路由方法路径以上配置生成的接口地址为:
GET http://localhost:3000/v1/usersGET http://localhost:3000/v1/users/:id
其中 @Get() 未声明路径,因此对应 /v1/users;@Get(':id') 声明了路由方法路径,因此对应 /v1/users/:id。
