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

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

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

示例
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言只 石皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值