我正在尝试将
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进口
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();
我找到了解决方案,因为这个问题与express有关(Nest.js在幕后使用express)我在这个线程中找到了解决方案错误:请求实体太大, 我所做的是修改
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://docs.nestjs.com/techniques/performance
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ bodyLimit: 10048576 }),
body-parser 定义的默认限制是 100kb: https://github.com/expressjs/body-parser/blob/0632e2f378d53579b6b2e4402258f4406e62ac6f/lib/types/json.js#L53-L55
希望这有帮助:)
对我来说这很有帮助,我将 100kb 设置为 50mb
这解决了我的问题,而且在nestjs中bodyparser现在已经被贬值,所以这可能是一个合适的解决方案。
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
不要直接使用body-parser,它会破坏nestjs的一些配置
根据https://github.com/nestjs/nest/issues/10471#issuecomment-1418091656
使用
app.useBodyParser
添加 body-parser 中间件
我是这样添加的:
import { json as expressJson, urlencoded as expressUrlEncoded } from 'express';
// You init your app here: app = await NestFactory.create(AppModule
if (app !== undefined) {
app.use(expressJson({ limit: '50mb' }));
app.use(expressUrlEncoded({ limit: '50mb', extended: true }));
}
它对我有帮助:
app.use(json({ limit: '50mb' }));