알 수 없는 필드
Coddy Node.js 여정의 TypeScript와 NestJS 섹션에 포함된 레슨. 17개 중 12번째.
클라이언트는 DTO에 언급되지 않은 필드(예: { "title": "x", "admin": true })를 보낼 수 있으며, 이 필드는 수정되지 않은 채 코드에 전달됩니다. ValidationPipe에는 이러한 필드를 처리하는 두 가지 옵션이 있습니다.
app.useGlobalPipes(
new ValidationPipe({ whitelist: true }),
);whitelist: true는 메서드가 본문을 받기 전에 검증 데코레이터가 없는 모든 필드를 제거합니다. forbidNonWhitelisted: true를 추가하면 파이프는 해당 본문을 거부하고, 400 오류와 함께 "property admin should not exist"를 반환합니다. forbidNonWhitelisted는 whitelist와 함께 사용할 때만 작동하며, 단독으로는 아무 효과가 없습니다.
추가 입력을 보내는 폼에는 조용히 제거하는 방식이 적합합니다. 거부하는 방식은 API 클라이언트에 titel과 같은 오타를 알려 줍니다.
챌린지
쉬움POST /tasks와CreateTaskDto필드를 사용해 요청해도 해당 필드의 이름을 명시하는 400 응답은 반환되지 않습니다.- 유효한 본문에는 여전히 201 응답이 반환됩니다.
POST /tasks에{ "title": "Book flights", "owner": "admin" }를 보내고, 그다음{ "title": "Book flights" }를 보내세요.
직접 해보기
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.