nestjs post请求提交数据量太大会报错 [ExceptionsHandler] request entity too large

背景

在传给后端接口的数据,是一个超过1.5mb的json字符串,通过nest filter的时候直接被拦截掉了,返回【 请求体太长】的错误。nestjs post请求提交数据量太大会报错 [ExceptionsHandler] request entity too large_第1张图片

还没有到达contraller,就直接被框架拦截掉了,

import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { ErrorCode } from '../shared/constants';

export class CommonException extends Error {
  constructor(public code: number, public message: string) {
    super();
  }
}

@Catch()
export class UncaughtExceptionFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: Error | CommonException, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const { httpAdapter } = this.httpAdapterHost;
    const { message = 'Internal Server Error' } = exception;

    const responseBody = {
      result_code: 500, // TODO: remove it
      result_message: message, // TODO: remove it
      code:
        exception instanceof CommonException
          ? exception.code
          : ErrorCode.UNCAUGHT_EXCEPTION, // 100
      msg: message,
    };

    httpAdapter.reply(ctx.getResponse(), responseBody, 200);
  }
}

解决

1、参考这个解决方案,Nest.js - request entity too large PayloadTooLargeError: request entity too large,引入bodyParser修改配置即可。(默认配置是比较小的)

import * as bodyParser from 'body-parser';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(bodyParser.json({limit: '50mb'}));
  app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
  await app.listen(3000);
}
bootstrap();

2、对我这个场景来说,传给后端的数据是可控的,所以我们可以考虑自行把新旧数据进行比对,只把被修改的数据传给后端即可。

你可能感兴趣的:(前端框架)