1、获取post请求的数据用@Body()参数装饰器获取数据,此外还有参数装饰器@Query、@Param()。
另外@Param()获取Params里的东西
2、在获取参数时,有事会需要定义请求数据格式,可以按照下面创建createPostDto类的方式来约束数据。
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
// 标识创建帖子的参数详情
class createPostDto{
//可以在swagger中显示
@ApiProperty({description:'帖子标题'})
title:string
//可以在swagger中显示
@ApiProperty({description:'帖子内容'})
content:string
}
@Controller('posts')
@ApiTags('帖子')
export class PostsController {
@Get()
@ApiOperation({summary:'显示博客列表'})
index() {
return [
{id:1111},
{id:13},
{id:14},
{id:1},
{id:37},
{id:26},
];
}
@Post()
@ApiOperation({summary:"创建帖子"})
//post请求
//:createPostDto是用来约束请求参数的,请求的参数要符合createPostDto类。
create(@Body() Body:createPostDto){
return{
success:true
}
}
//get请求
// create(@query() Body){
// return{
// success:true
// }
// }
@Get(':id')
detail(){
return{
id:1,
title:'aaaaa'
}
}
}
示例

本文介绍了如何使用NestJS框架通过@Body、@Query和@Param装饰器处理POST和GET请求,创建Post DTO约束数据格式,并展示如何为API操作提供详细的Swagger文档。重点讲解了参数获取和数据验证的最佳实践。
1347

被折叠的 条评论
为什么被折叠?



