Search code examples
nestjsmultipartform-datamulterdto

Empty object when using DTO with multipart/form-data on NestJS


In my backend, I have this endpoint:

@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
  @UploadedFiles() files: Array<Express.Multer.File>,
  @Body() body: MyDto,
  ) {
  console.log(body);
  console.log(files);
}

MyDto is as simple as:

export class MyDto {

  year: string
}

When I send a multipart/form-data request (tried with code on Firefox, Chrome and with Postman) only with the year field or together with one or more files, I get this from the first console.log (the one that prints the body):

MyDto {}

When I remove the typing from the body and the endpoint becomes:

@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
  @UploadedFiles() files: Array<Express.Multer.File>,
  @Body() body,
  ) {
  console.log(body);
  console.log(files);
}

The body is shown as:

[Object: null prototype] { year: '2022' }

The files variable is always correct.
How can I set the type for the body?

My main.ts is as follows:

const app = await NestFactory.create(AppModule, {
    logger: ['log', 'error'],
  });
  app.enableCors();
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
    })
  );
  app.use(bodyParser.json({limit: '1mb'}));
  app.use(bodyParser.urlencoded({limit: '1mb', extended: true}));
  const appVersion = '0.0.1';
  const port = process.env.PORT || 3000;
  await app.listen(port);

Solution

  • You're missing any decorator on the year property of the MyDto class, and because you have whitelist: true, class-validator will strip the non-whitelisted values (i.e. the values that don't match up with a decorated property of the class)