본문 바로가기
Back-End/NestJs

[NestJS] must be a number conforming to the specified constraints - body dto 타입 에러 해결

by 흐암졸령 2022. 6. 11.
반응형

[ 문제점 ]

 Nest Js에서 post나 put을 할 때 body에 데이터를 담아서 보낸다. 이때 dto로 검증을 하는데 id는 number을 받기 위해서 다음과 같은 dto를 만들었다.

import { IsNumber, IsOptional, IsString } from 'class-validator';

export class UpdatePlanDto {
  @IsNumber()
  readonly id: number;

  @IsOptional()
  @IsString()
  readonly date: string;
}

이렇게 만들고 요청을 보내니 다음과 같은 400오류가 뜨면서 작동하지 않았다.

Postman response


[ 해결 방법 ]

 이러한 오류가 나온 이유는 message에도 설명해주지만 id의 type이 number가 아니라는 것이다. 받은 데이터를 number로 변환해주어야지 오류가 사라진다. 따라서 dto에서 type 데코레이터를 사용해 number로 타입을 바꾸어준다.

import { IsNumber, IsOptional, IsString } from 'class-validator';
import { Type } from 'class-transformer';

export class UpdatePlanDto {
  @Type(() => Number)
  @IsNumber()
  readonly id: number;

  @IsOptional()
  @IsString()
  readonly date: string;
}

그러면 type이 number로 바뀌면서 정상적으로 작동하게 된다.

 

반응형

댓글