Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
How to handle unexpected data from the post request body in NestJS

In NestJS official tutorial of validation. We can handle wrong data type from client side post request.

// dtos/CreateUserDto.ts

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}
// controllers/user.controller.ts

@Post()
async createUser(@Body() body: CreateUserDto) {
 return body;
}

When I create a post request like

 curl -X POST 'http://domain/user' -d '{"email": "john", "password": "changeme"}' -H "Content-Type: application/json"

I will get an expected error return.

{
    "statusCode": 400,
    "message": [
        "email must be an email"
    ],
    "error": "Bad Request"
}

my concern is an scenario that post request with unexpected data

 curl -X POST 'http://domain/user' -d '{"email": "john@example.com", "password": "changeme", "foo": "bar"}' -H "Content-Type: application/json"

I will get a return.

{
"email": "john@example.com",
"password": "changeme",
"foo": "bar"
}

I suppose the key foo would be deleted or return a system error, but it doesn't do that.

What is the best way to handle this condition ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since NestJS is using class-validator you can pass all the properties to the validation pipe that are supported by class-validator options.

ValidatorOptions {
  skipMissingProperties?: boolean;
  whitelist?: boolean;
  forbidNonWhitelisted?: boolean;
  groups?: string[];
  dismissDefaultMessages?: boolean;
  validationError?: {
    target?: boolean;
    value?: boolean;
  };

  forbidUnknownValues?: boolean;
  stopAtFirstError?: boolean;
}

If you want not just strip values but throw an error when an unexpected value is passed you can use forbidUnknownValues: true.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda