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

示例
在这里插入图片描述

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐