欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

nest.js-学习记录:4、post请求和数据传输对象DTO

时间:2023-07-30

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' } }}

示例

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。