Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js - request entity too large PayloadTooLargeError: request entity too large

I'm trying to save a JSON into a Nest.js server but the server crash when I try to do it, and this is the issue that I'm seeing on the console.log:

[Nest] 1976 - 2018-10-12 09:52:04 [ExceptionsHandler] request entity too large PayloadTooLargeError: request entity too large

One thing is the size of the JSON request is 1095922 bytes, Does any one know How in Nest.js increase the size of a valid request? Thanks!

like image 473
Alexisvt Avatar asked Oct 12 '18 16:10

Alexisvt


4 Answers

I found the solution, since this issue is related to express (Nest.js uses express behind scene) I found a solution in this thread Error: request entity too large, What I did was to modify the main.ts file add the body-parser dependency and add some new configuration to increase the size of the JSON request, then I use the app instance available in the file to apply those changes.

import { NestFactory } from '@nestjs/core';
import * as bodyParser from 'body-parser';

import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useStaticAssets(`${__dirname}/public`);
  // the next two lines did the trick
  app.use(bodyParser.json({limit: '50mb'}));
  app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
  app.enableCors();
  await app.listen(3001);
}
bootstrap();
like image 85
Alexisvt Avatar answered Nov 09 '22 10:11

Alexisvt


you can also import urlencoded & json from express

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { urlencoded, json } from 'express';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api');
  app.use(json({ limit: '50mb' }));
  app.use(urlencoded({ extended: true, limit: '50mb' }));
  await app.listen(process.env.PORT || 3000);
}
bootstrap();
like image 38
shahidfoy Avatar answered Nov 09 '22 10:11

shahidfoy


The solution that solved for me was to increase bodyLimit. Source:https://www.fastify.io/docs/latest/Server/#bodylimit

const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ bodyLimit: 10048576 }),
like image 12
Brenner Batista Avatar answered Nov 09 '22 09:11

Brenner Batista


The default limit defined by body-parser is 100kb: https://github.com/expressjs/body-parser/blob/0632e2f378d53579b6b2e4402258f4406e62ac6f/lib/types/json.js#L53-L55

Hope this helps :)

For me It helped and I set 100kb to 50mb

like image 2
saddam Avatar answered Nov 09 '22 11:11

saddam