控制器
装饰器 | 请求 类型 | 对应值 |
---|---|---|
@Get('id/:id/name/:name') | Get | |
@Post() | Post | |
@Headers(key,value) | Headers | req.headers/req.headers[name] |
@HttpCode(200) | 直接返回状态码 | |
@Redirect('https://nodejs.com', 302) | 重定向 URL | |
@Controller({ host: ':account.example.com' }) | 子域路由 | |
参数装饰器 | ||
@Query(key?: string) | Get 请求 | req.query/req.query[key] |
@Body(key?: string) | Post 请求 | req.body/req.body[key] |
@Param(key?: string) | Get 请求(Path 方式) | req.params/req.params[key] |
@UploadedFile(fileName?: string) | file | req.file |
@UploadedFiles(formName?: string) | files | req.files |
@Session() | session | req.session |
底层 | ||
@Request() | 全部请求 | req |
@Response() | 返回对象 | res |
路由通配符
NestJS 也支持基于模式的路由。例如,星号(*)可用作通配符,以匹配路径末尾路由中的任意字符组合。在以下示例中,对于任何以 abcd/ 开头的路由,都将执行 findAll() 方法,无论后面有多少个字符。
@Get('abcd/*')
findAll() {
return 'This route uses a wildcard';
}
重定向
有时你可能想要动态确定 HTTP 状态代码或重定向 URL。通过返回遵循 HttpRedirectResponse 接口(来自 @nestjs/common)的对象来完成此操作。
@Get('docs')
@Redirect('https://nest.nodejs.cn', 302)
getDocs(@Query('version') version) {
if (version && version === '5') {
return { url: 'https://nest.nodejs.cn/v5/' };
}
}
子域路由
@Controller({ host: ':account.example.com' })
- 这表示当访问的域名形如 xxx.example.com 时,这个控制器才会被激活。
- :account 是一个参数,可以匹配任何二级域名部分,并赋值到 account 上。
- @HostParam 修饰器用于提取 host(主机名)里的参数(前面定义的 :account)。
@Controller({ host: ':account.example.com' })
export class AccountController {
@Get()
getInfo(@HostParam('account') account: string) {
return account;
}
}
全局参数验证管道
- @UsePipes 是 NestJS 的装饰器,用于给控制器、路由处理程序(handler)应用“管道(Pipe)”。
- ValidationPipe 是 NestJS 官方提供的参数验证管道,用于校验请求体、请求参数是否符合你定义的 DTO(数据传输对象)格式。
- { transform: true } 是 ValidationPipe 的一个配置选项,表示将输入的原始数据自动“转换”为你希望的数据类型。
@UsePipes(new ValidationPipe({ transform: true }))