【问题标题】:Nest.js - request entity too large PayloadTooLargeError: request entity too largeNest.js - 请求实体太大 PayloadTooLargeError:请求实体太大
【发布时间】:2019-03-17 22:43:19
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js nestjs


    【解决方案1】:

    你也可以从 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();
    

    【讨论】:

    【解决方案2】:

    我找到了解决方案,因为这个问题与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();
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 这是 Nest Fastify 应用的正确解决方案。
      【解决方案4】:

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

      希望这会有所帮助:)

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

      【讨论】:

        猜你喜欢
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 2019-11-27
        • 2022-11-27
        • 2012-02-12
        • 2016-11-08
        • 2014-12-30
        • 2011-04-12
        相关资源
        最近更新 更多