请求正文中的布尔参数在

请求正文中的布尔参数在

本文介绍了请求正文中的布尔参数在 NestJS api 中始终为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 API 中考虑这个端点:

Consider this endpoint in my API:

@Post('/convert')
  @UseInterceptors(FileInterceptor('image'))
  convert(
    @UploadedFile() image: any,
    @Body(
      new ValidationPipe({
        validationError: {
          target: false,
        },
        // this is set to true so the validator will return a class-based payload
        transform: true,
        // this is set because the validator needs a tranformed payload into a class-based
        // object, otherwise nothing will be validated
        transformOptions: { enableImplicitConversion: true },
      }),
    )
    parameters: Parameters,
  ) {
    return this.converterService.start(image, parameters);
  }

设置为 parameters 参数的请求正文包含一个名为 laserMode 的属性,它应该是一个布尔类型,它在 参数 DTO:

The body of the request, which is set to parameters argument, contains a property called laserMode that should be a boolean type, it is validated like such on the parameters DTO:

  @IsDefined()
  @IsBoolean()
  public laserMode: boolean;

现在奇怪的部分,当从 PostMan 发送请求时:

now the strange part, when a send a request from PostMan where:

  1. laserMode = false
  2. laserMode = cool(布尔值以外的字符串)
  1. laserMode = false
  2. laserMode = cool (a string other the boolean value)

我注意到 laserMode 始终设置为 true,这是在验证过程完成之后,因为当我 console.log 实例类的构造函数中的参数

I noticed that laserMode is always set to true and this is after the validation process is completed because when I console.log the instance of Parameter in the constructor of the class

export class Parameters {
  ...
  constructor() {
    console.log('this :', this);
  }
  ...
}

我没有看到该属性!

注意:当从请求中移除laserMode时,返回预期的验证错误(应定义,应为布尔值).

// the logged instance 'this' in the constructor
this : Parameters {
  toolDiameter: 1,
  sensitivity: 0.95,
  scaleAxes: 200,
  deepStep: -1,
  whiteZ: 0,
  blackZ: -2,
  safeZ: 2,
  workFeedRate: 3000,
  idleFeedRate: 1200,
  laserPowerOn: 'M04',
  laserPowerOff: 'M05',
  invest: Invest { x: false, y: true }
}
// the logged laserMode value in the endpoint handler in the controller
parameters.laserMode in controller : true
// the logged laser value from the service
parameters.laserMode in service : true

  • 检查拼写错误
  • 使用 Vue 应用程序而不是邮递员时会注意到相同的结果.所以!!?
  • 推荐答案

    这是由于选项 enableImplicitConversion.显然,所有字符串值都被解释为 true,甚至字符串 'false'.

    This is due to the option enableImplicitConversion. Apparently, all string values are interpreted as true, even the string 'false'.

    有一个问题要求改变class-变压器.

    这篇关于请求正文中的布尔参数在 NestJS api 中始终为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:36