主题
路由
HTTP 路由由三部分依次组合:
md
全局路由前缀 + Controller 路由前缀 + 路由方法路径Controller 与方法路径
@Controller('路径前缀') 声明一组接口的公共前缀;@Get('子路径')、@Post() 等与 HTTP 方法装饰器拼成完整路径。
ts
import { Controller, Get } from '@nestjs/common'
@Controller('hello')
export class HelloController {
@Get('me')
me() {
return 'ok'
}
}@Controller('hello') + @Get('me') → GET /hello/me(若设置了全局前缀 v1,则为 GET /v1/hello/me)。
常用方法装饰器:@Get()、@Post()、@Put()、@Patch()、@Delete()。控制器保持轻薄:接收输入、调用服务、返回结果;业务规则放在 Service。
@Controller('users') 只描述当前 Controller 的业务路径,不需要再写全局前缀。
ts
import { Controller, Get, Param } from '@nestjs/common'
@Controller('users')
export class UsersController {
@Get()
findAll() {}
@Get(':id')
findOne(@Param('id') id: string) {}
}在全局前缀为 v1 时:GET /v1/users、GET /v1/users/:id。
全局路由前缀
在 main.ts 调用 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()健康检查等不需要全局前缀的路由,可用 exclude 排除:
ts
import { RequestMethod } from '@nestjs/common'
app.setGlobalPrefix('v1', {
exclude: [{ path: 'health', method: RequestMethod.GET }],
})此时 GET /health 不带全局前缀,其他路由仍以 /v1 开头。
