作用:处理传入的请求和向客户端返回相应。
特征:多个路由就有多个控制器
装饰器:与数据关联,将请求绑定到控制器
语法:@xxx 如:@Controller
命令:创建控制器 nest g controller xxx
@Controller('cats') :定义请求的路由前缀,如: /cats 、
@Get(profile):写在方法之前,用户指定路由的请求方式,与controller前缀链接,如:/cats/profile
返回值响应的两种概念:
1.1对象和数组:返回值会被自动序列化为JSON
1.2基本类型:返回值为对应的值,不会序列化
2.1@Res(xxx),注入特定类库的相应对应,如express,则您可以使用 `response.status(200).send()` 构建响应
函数参数:
@Param() params: 其中Params代表装饰器,此处为:xx等动态路由参数的获取对象,params为函数内使用时的操作变量,则使用时为:${params.xx}
@param('id') id: 相当于结构Params上的id 并命名为id 使用时直接${id}
@Query() query: ListAllEntities: 奖ListALLEntities获取的DTO值赋值给query。
DTO:数据传输对象,即对象,一般通过interface、class来定义。由于ts的接口类型数据使用过程中会被删除,所以Nest不能在运行是引用它;
DTO类写法:
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
DTO使用,代表/路由被访问必须传cateCatDto的数据
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return '...'
}
请求的使用demo
/* cats.controller.ts */
import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
@Get()
findAll(@Query() query: ListAllEntities) {
return `This action returns all cats (limit: ${query.limit} items)`;
}
@Get(':id')
findOne(@Param('id') id: string) {
return `This action returns a #${id} cat`;
}
@Put(':id')
update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {
return `This action updates a #${id} cat`;
}
@Delete(':id')
remove(@Param('id') id: string) {
return `This action removes a #${id} cat`;
}
}
模块:控制属于模块,即@Module()中包含controllers数组。
@Module({
controllers: [CatsController]
})
`passthrough` 选项设置为 `true`,解决Nest功能失效和兼容性问题
如:
@Get() findAll(@Res({ passthrough: true }) res: Response) { res.status(HttpStatus.OK); return []; }