【问题标题】:Nest js optional body parameter嵌套js可选body参数
【发布时间】:2021-05-13 06:26:34
【问题描述】:

您好,我有 Nest 应用程序 dto:

export class TestDto {
  @IsNotEmpty()
  id: number;

  @IsNotEmpty()
  slug: string;

  @IsNotEmpty()
  size: number;
} 

和发布请求:

  @Post(':id/start')
  async startTest(
    @Param('id') id: number,
    @Request() req,
    @Body() testDto?: TestDto
  ): Promise<RoomDto | string> {
    return await this.roomsService.startTest(id, testDto);
  }

我想从 body 中选择 testDto,但发送请求时出现错误:

{
    "statusCode": 400,
    "message": [
        "slug should not be empty",
        "size should not be empty"
    ],
    "error": "Bad Request"
}

如何实现这样的目标?

【问题讨论】:

    标签: javascript nestjs


    【解决方案1】:

    您必须将 IsNotEmpty 装饰器更改为 IsOptional,当您将问号添加到参数时,您是在告诉 Typescript 该值可以是未定义的,这在运行时无关紧要。

    您可以在此处查看允许的装饰器:https://github.com/typestack/class-validator#validation-decorators

    结果 DTO 将是这样的:

    export class TestDto {
      @IsNotEmpty()
      id: number;
    
      @IsOptional()
      slug?: string;
    
      @IsOptional()
      size?: number;
    } 

    记得从 class-validator 包中导入 IsOptional。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 2013-02-18
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2015-12-26
      相关资源
      最近更新 更多