Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
PayloadTooLargeError: entidad de solicitud demasiado grande. ¿Cómo resolverlo en NestJS?

Necesito enviar la solicitud que contiene una cadena base64 y es demasiado grande (probablemente, alrededor de 2 mb).

Pero el servidor lanza la siguiente excepción, cómo evitar este error:

 [Nest] 1666 - 11/01/2021, 1:50:58 PM ERROR [ExceptionsHandler] request entity too large gateway-client | PayloadTooLargeError: request entity too large gateway-client | at readStream (/srv/app/node_modules/raw-body/index.js:155:17) gateway-client | at getRawBody (/srv/app/node_modules/raw-body/index.js:108:12) gateway-client | at read (/srv/app/node_modules/body-parser/lib/read.js:77:3) gateway-client | at jsonParser (/srv/app/node_modules/body-parser/lib/types/json.js:135:5) gateway-client | at Layer.handle [as handle_request] (/srv/app/node_modules/express/lib/router/layer.js:95:5) gateway-client | at trim_prefix (/srv/app/node_modules/express/lib/router/index.js:317:13) gateway-client | at /srv/app/node_modules/express/lib/router/index.js:284:7 gateway-client | at Function.process_params (/srv/app/node_modules/express/lib/router/index.js:335:12) gateway-client | at next (/srv/app/node_modules/express/lib/router/index.js:275:10) gateway-client | at expressInit (/srv/app/node_modules/express/lib/middleware/init.js:40:5)

Mi main.ts incluye:

 async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule); // app.enableCors({ // origin: '*', // }); const config = new DocumentBuilder() .setTitle('API client gateway') .setDescription('API client gateway full documentation') .setVersion('v0.0.1') .addTag('') .addBearerAuth( { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', name: 'JWT', description: 'Enter JWT token', in: 'header', }, 'jwt-token', ) .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('/api/docs', app, document); await app.init(); app.use(express.json({limit: "50mb"})) //For JSON requests app.use(express.urlencoded({ limit: "50mb", extended: false })); await app.listen(AppConfig.Port); } bootstrap();
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En su archivo main.ts (muy probablemente el método bootstrap() ) obtenga una instancia de Express App y configure el analizador JSON con límite:

 import { json } from 'body-parser'; async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: false }); app.use(json({ limit: '5mb' })); ... }

EDITAR: si está accediendo a la aplicación a través de un proxy (nginx, por ejemplo), asegúrese de que también se permite el mismo límite.

about 4 years ago · Juan Pablo Isaza Report

0

si desea utilizar una versión más idiomática de body-parser (después de desactivarlo en su función de bootstrap ):

 // json-body-parser.middleware.ts import { NestMiddleware } from '@nestjs/common'; import bodyParser from 'body-parser'; type JsonBodyParserOpts = bodyParser.OptionsJson; // As we're not using DI, we don't need to mark this as Injectable export class JsonBodyParserMiddleware implements NestMiddleware { private readonly options: JsonBodyParserOpts = { limit: '5mb', }; use = bodyParser.json(this.options); }
 // in your main/root module // ... export class AppModule implements NestModule { configure(middlewareConsumer: MiddlewareConsumer): void { middlewareConsumer .apply(JsonBodyParserMiddleware) .forRoutes({ path: '*', method: RequestMethod.ALL, }); } }

Prefiero evitar app.use tanto como pueda para permitir que el bootstrap funcione más limpio.

O podría hacerlo configurable dinámicamente desde el exterior, haciendo algo como esto .

Obtenga más información sobre los middlewares de Nestjs aquí: https://docs.nestjs.com/middleware

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!