Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda