1.快速生成
shell
nest g controller [name]
# or
nest g controller [name] --no-spec
2.基础语法
ts
// cats.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
3.@Handler
3-1.@Controller
@Controller
用来将路由分组,并且定义路由前缀。
譬如:
@Controller()
表示/
@Controller('cats')
表示/cats
它的完整用法如下:
ts
@Controller(path)
@Controller({ path })
@Controller({ host })
@Controller({ path, host })
4.@Method
4-1.请求方式
@Get()
@Post()
@Put()
@Delete()
@Patch()
@Head()
@Options()
@All()
以上所有方法。
4-2.状态码
@HttpCode()
ts
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
4-3.重定向
@Redirect(url, statusCode)
ts
@Get()
@Redirect('https://nestjs.com', 301)
如果要动态的重定向,那么需要返回 { url: string, statusCode: number }
这样的对象:
ts
@Get('docs')
@Redirect('https://docs.nestjs.com', 302)
getDocs(@Query('version') version) {
if (version && version === '5') {
return { url: 'https://docs.nestjs.com/v5/' };
}
}
5.@Util
5-1.@Request() / @Req()
@Request()
和 @Req()
都是用来获取 request
对象的。
ts
@Get()
getAll(@Request() req): any {
console.log(req.headers)
return req.user
}
等同于:
ts
@Get()
getAll(@Req() req): any {
return req.user
}
5-2.@Response() / @Res()
@Response()
和 @Res()
都是用来获取 response
对象的。
ts
@Get()
customResponse(@Res() res): any {
res.status(200).json({ message: 'Hello' })
}
5-3.@Next()
@Next()
用于获取 next
对象。
ts
@Get()
withNext(@Req() req, @Res() res, @Next() next): any {
if (!req.user) return next(new Error('No user'))
res.send('OK')
}
5-4.@Session()
@Session()
用于获取 session
对象,需要配合 express-session 使用。
ts
@Get('profile')
getProfile(@Session() session: Record<string, any>) {
return session.user
}
5-5.@Param(key?: string)
@Param()
用于获取路由参数。
ts
@Get(':id')
getUser(@Param('id') id: string) {
return `User ID: ${id}`
}
// 如果不传参数,返回整个 req.params 对象
@Get(':id/:name')
getUserInfo(@Param() params) {
return params // { id: '123', name: 'Tom' }
}
5-6.@Body(key?: string)
@Body()
用于获取请求体数据。
ts
@Post()
createUser(@Body() body) {
return body // { name: 'Tom', age: 18 }
}
@Post()
createUser(@Body('name') name: string) {
return `Name: ${name}`
}
5-7.@Query(key?: string)
@Query()
用于获取查询参数。
ts
@Get()
getAll(@Query() query) {
return query // { page: '1', size: '10' }
}
@Get()
getPage(@Query('page') page: string) {
return `Page: ${page}`
}
5-8.@Headers(name?: string)
@Headers()
用于获取请求头。
ts
@Get()
getAllHeaders(@Headers() headers) {
return headers
}
@Get()
getHeader(@Headers('user-agent') ua: string) {
return ua
}
5-9.@Ip()
@Ip()
用于获取客户端的 IP
地址。
ts
@Get()
getIp(@Ip() ip: string) {
return `Client IP: ${ip}`
}
5-10.@HostParam(name?: string)
@HostParam()
从 host
中提取子域参数,例如 :account.example.com
中的 account
。
需要配合路由中的 @Controller({ host: ':account.example.com' })
变量使用。
ts
@Controller({ host: ':account.example.com' })
export class AccountController {
@Get()
getInfo(@HostParam('account') account: string) {
return account;
}
}
{ host: ':account.example.com' }
表示这个控制器只响应访问*.example.com
的请求。:account
是一个参数化的子域名,类似于路由中的:id
。当访问abc.example.com
时,:account
的值就是'abc'
。