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

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

我正在尝试将 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 如何增加有效请求的大小吗?谢谢!

我找到了解决方案,因为这个问题与 express 有关(Nest.js 在后台使用 express)我在这个线程 Error: request entity too large 中找到了解决方案, 我所做的是修改 main.ts 文件添加 body-parser 依赖项并添加一些新配置以增加 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();

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

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

您还可以从 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();

body-parser 定义的默认限制是 100kb: https://github.com/expressjs/body-parser/blob/0632e2f378d53579b6b2e4402258f4406e62ac6f/lib/types/json.js#L53-L55

希望对您有所帮助:)

对我来说很有帮助,我将 100kb 设置为 50mb