Nest.js - 请求实体太大PayloadTooLargeError:请求实体太大

Ale*_*svt 6 javascript node.js nestjs

我正在尝试将其保存JSON到Nest.js服务器中,但是当我尝试执行此操作时服务器崩溃,这是我在console.log上看到的问题:

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

一件事是JSON请求的大小是1095922字节,有没有人知道如何在Nest.js中增加有效请求的大小?谢谢!

小智 30

您也可以从 express导入urlencoded和导入json

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();
Run Code Online (Sandbox Code Playgroud)

  • 比添加额外的库更好的解决方案 (3认同)
  • @NenadJovicic 实际上,“body-parser”已经被“express”包含和使用,NestJS 的作者建议使用它:https://github.com/nestjs/nest/issues/529#issuecomment-376576929 所以它很可能是相同的。 (2认同)

Ale*_*svt 13

我找到了解决方案,因为这个问题与express有关(Nest.js使用express后台场景)我在这个帖子中找到了一个解决方案错误:请求实体太大了,我做的是修改main.ts文件添加body-parse依赖项并添加一些新的配置增加JSON请求的大小,然后我使用app文件中可用的实例来应用这些更改.

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();
Run Code Online (Sandbox Code Playgroud)


小智 8

为我解决的解决方案是增加 bodyLimit。来源:https : //www.fastify.io/docs/latest/Server/#bodylimit

const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ bodyLimit: 10048576 }),
Run Code Online (Sandbox Code Playgroud)

  • 这是 Nest Fastify 应用程序的正确解决方案。 (2认同)