【问题标题】:DTO in nest js accepting more parameter as compared to DTO与 DTO 相比,嵌套 js 中的 DTO 接受更多参数
【发布时间】:2020-01-30 19:13:14
【问题描述】:

我有一个 DTO


export class UpdateUserRoleDTO {
  @ApiProperty()
  @IsNotEmpty()
  readonly userId:number;

  @ApiProperty()
  @IsNotEmpty()
  @IsNumber()
  readonly roleId: number;
}

我的控制器是这样的

@UsePipes(new ValidationPipe())
  @Post('/update')
  async updateUser(@Body() updateUserDto: UpdateUserDTO): Promise<User> {
    return await this.userService.updateUser(updateUserDto);
  }

每当客户端发送带有以下负载的请求时

payloadObj = {
   userId : 1,
   roleId : 1,
   xyz : 'assddcds',
   someotherkey : 'fsdvs'
}

它正在访问我的服务文件。我想避免这种情况,确保只传递 DTO 中提到的参数,否则它应该给出 400

【问题讨论】:

  • @UsePipes(new ValidationPipe({forbidNonWhitelisted: true, whitelist: true}) 将此装饰器添加到您的控制器中
  • 只有两个旁注:无需等待服务,而不仅仅是返回承诺,而且您通常不需要 API 中名为“/update”的路由,因为您已经有了 http 请求方法“post”来区分动作。

标签: nestjs


【解决方案1】:

鉴于您的代码,我会将设置为 truewhitelist 选项传递给您正在实例化的 ValidationPipe,就像在您的控制器中一样:

controller.ts

@UsePipes(new ValidationPipe({ whitelist: true }))
@Post('/update')
async updateUser(@Body() updateUserDto: UpdateUserDTO): Promise<User> {
  return await this.userService.updateUser(updateUserDto);
}

这应该可以完成工作。

如果有帮助,请告诉我,否则请随时发表评论并分享您的发现;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2020-09-29
    相关资源
    最近更新 更多