iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔖

Resolving the "Field value too long" Error in NestJS POST Requests

に公開

Introduction

I created a backend with NestJS, and when I uploaded a large image file to the user profile update API I created, the following error was returned from the API (400 Bad Request):

{
	"message": "Field value too long",
	"error": "Bad Request",
	"statusCode": 400
}

Solution

For example, suppose you have a module.ts like the following:

src/modules/user/user.module.ts
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { HttpModule } from '@nestjs/axios';

@Module({
  imports: [HttpModule],
  controllers: [UserController],
  providers: [UserService],
})

Rewrite the file as follows to increase the upper limit for the file upload size:

src/modules/user/user.module.ts
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { HttpModule } from '@nestjs/axios';
import { MulterModule } from '@nestjs/platform-express';

// Maximum file upload size
const MULTER_UPLOAD_FIELD_SIZE = 5 * 1024 * 1024; // 5MB

@Module({
  imports: [
    HttpModule,
    MulterModule.register({
      limits: { fieldSize: MULTER_UPLOAD_FIELD_SIZE },
    }),
  ],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

Remarks

As mentioned in the official NestJS documentation, NestJS uses a module based on the multer middleware package for Express for file uploads.

Looking at the official Express documentation, the fieldSize is 1MB by default, so we are extending that limit.

References

Field value too long · Issue #436 · expressjs/multer

Discussion