node.js 错误:请求实体太大

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19917401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:15:33  来源:igfitidea点击:

Error: request entity too large

javascriptnode.jshttpexpress

提问by mike james

I'm receiving the following error with express:

我收到快递的以下错误:

Error: request entity too large
    at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15)
    at json (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/json.js:60:5)
    at Object.bodyParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:53:5)
    at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.cookieParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
    at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.logger (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/logger.js:158:5)
    at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.staticMiddleware [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)
    at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
TypeError: /Users/michaeljames/Documents/Projects/Proj/mean/app/views/includes/foot.jade:31
    29| script(type="text/javascript", src="/js/socketio/connect.js")
    30| 
  > 31| if (req.host='localhost')
    32|     //Livereload script rendered 
    33|     script(type='text/javascript', src='http://localhost:35729/livereload.js')  
    34| 

Cannot set property 'host' of undefined
    at eval (eval at <anonymous> (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:152:8), <anonymous>:273:15)
    at /Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:153:35
    at Object.exports.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:197:10)
    at Object.exports.renderFile (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:233:18)
    at View.exports.renderFile [as engine] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:218:21)
    at View.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/view.js:76:8)
    at Function.app.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/application.js:504:10)
    at ServerResponse.res.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/response.js:801:7)
    at Object.handle (/Users/michaeljames/Documents/Projects/Proj/mean/config/express.js:82:29)
    at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:188:17)

POST /api/0.1/people 500 618ms

I am using meanstack. I have the following use statements in my express.js

我正在使用meanstack。我的 express.js 中有以下 use 语句

//Set Request Size Limit
app.use(express.limit(100000000));

Within fiddler I can see the content-length header with a value of: 1078702

在 fiddler 中,我可以看到内容长度标头的值为:1078702

I believe this is in octets, this is 1.0787 megabytes.

我相信这是八位字节,这是 1.0787 兆字节。

I have no idea why express is not letting me post the json array I was posting previously in another express project that was not using the mean stack project structure.

我不知道为什么 express 不让我发布我之前在另一个未使用均值堆栈项目结构的 express 项目中发布的 json 数组。

回答by Samuel Bolduc

I had the same error recently, and all the solutions I've found did not work.

我最近遇到了同样的错误,我找到的所有解决方案都不起作用。

After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'}));did set the limit correctly.

经过一番挖掘,我发现该设置app.use(express.bodyParser({limit: '50mb'}));确实正确设置了限制。

When adding a console.log('Limit file size: '+limit);in node_modules/express/node_modules/connect/lib/middleware/json.js:46and restarting node, I get this output in the console:

当添加console.log('Limit file size: '+limit);node_modules/express/node_modules/connect/lib/middleware/json.js:46并重新启动节点,我在控制台中的输出:

Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002

We can see that at first, when loading the connectmodule, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.logis called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large.

我们可以看到,一开始加载connect模块时,限制设置为1mb(1048576字节)。然后当我设置限制时,console.log再次调用,这次限制是 52428800 (50mb)。但是,我仍然得到一个413 Request entity too large.

Then I added console.log('Limit file size: '+limit);in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10and saw another line in the console when calling the route with a big request (before the error output) :

然后我说console.log('Limit file size: '+limit);node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10,看到调用带有很大的请求路由(错误输出之前)时,控制台另一条线:

Limit file size: 1048576

This means that somehow, somewhere, connectresets the limit parameter and ignores what we specified. I tried specifying the bodyParserparameters in the route definition individually, but no luck either.

这意味着不知何故,在某处,connect重置了限制参数并忽略了我们指定的内容。我尝试bodyParser单独指定路由定义中的参数,但也没有运气。

While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js:

虽然我没有找到任何合适的方法来永久设置它,但您可以直接在模块中“修补”它。如果您使用的是 Express 3.4.4,请在第 46 行添加以下内容node_modules/express/node_modules/connect/lib/middleware/json.js

limit = 52428800; // for 50mb, this corresponds to the size in bytes

The line number might differ if you don't run the same version of Express. Please note that this is bad practiceand it will be overwrittenif you update your module.

如果您不运行相同版本的 Express,行号可能会有所不同。请注意,这是不好的做法,如果您更新模块,它将被覆盖

So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.

所以这个临时解决方案现在有效,但是一旦找到解决方案(或修复模块,以防它是模块问题),您应该相应地更新您的代码。

I have opened an issue on their GitHubabout this problem.

在他们的 GitHub 上打开了一个关于这个问题的问题。

[edit - found the solution]

[编辑 - 找到解决方案]

After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));, but afterapp.use(express.json());. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json(). Moving bodyParserabove it did the trick.

经过一番研究和测试,我发现在调试的时候,我添加了app.use(express.bodyParser({limit: '50mb'}));,但是app.use(express.json());. Express 然后会将全局限制设置为 1mb,因为他在运行脚本时遇到的第一个解析器是express.json(). bodyParser在它上面移动就成功了。

That said, the bodyParser()method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :

也就是说,该bodyParser()方法将在 Connect 3.0 中弃用,不应使用。相反,您应该显式声明您的解析器,如下所示:

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

In case you need multipart (for file uploads) see this post.

如果您需要多部分(用于文件上传),请参阅此帖子

[second edit]

[第二次编辑]

Note that in Express 4, instead of express.json()and express.urlencoded(), you must require the body-parsermodule and use its json()and urlencoded()methods, like so:

需要注意的是在快递4,而不是express.json()express.urlencoded(),你必须要求身体解析器模块,并使用其json()urlencoded()方法,就像这样:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

If the extendedoption is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option). This is because this option will be required in the next version and will notbe optional anymore. For more info on the extendedoption, you can refer to the readmeof body-parser.

如果extended没有为 明确定义该选项bodyParser.urlencoded(),则会抛出警告 ( body-parser deprecated undefined extended: provide extended option)。这是因为该选项在下一个版本中将是必需的,并且不再是可选的。有关更多信息extended选项,可以参考自述body-parser

[third edit]

[第三次编辑]

It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):

似乎在 Express v4.16.0 之后,我们可以回到最初的做法(感谢@GBMan 的提示):

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

回答by slorenzo

I use Express 4.

我使用 Express 4。

In my case it was not enough to add these lines :

在我的情况下,添加这些行是不够的:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

I tried adding the parameterLimit option on urlencoded function as the documentation says and error no longer appears.

我尝试在 urlencoded 函数上添加 parameterLimit 选项,如文档所述,错误不再出现。

The parameterLimit option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to 1000.

parameterLimit 选项控制 URL 编码数据中允许的最大参数数。如果请求包含的参数多于该值,则会向客户端返回 413。默认为 1000。

Try with this code:

尝试使用此代码:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

回答by Alexander

If someone tried all the answers, but hadn't had any success yet and uses NGINX to host the site add this line to /etc/nginx/sites-available

如果有人尝试了所有答案,但还没有取得任何成功并使用 NGINX 托管站点,请将此行添加到 /etc/nginx/sites-available

client_max_body_size 100M; #100mb

回答by Peter Lyons

I don't think this is the express global size limit, but specifically the connect.json middleware limit. This is 100kb by default when you use express.bodyParser()and don't provide a limitoption.

我不认为这是明确的全局大小限制,而是特别是connect.json 中间件限制。当您使用express.bodyParser()且不提供limit选项时,默认为 100kb 。

Try:

尝试:

app.post('/api/0.1/people', express.bodyParser({limit: '5mb'}), yourHandler);

回答by Mohanad Obaid

in my case .. setting parameterLimit:50000fixed the problem

在我的情况下..设置parameterLimit:50000解决了问题

app.use( bodyParser.json({limit: '50mb'}) );
app.use(bodyParser.urlencoded({
  limit: '50mb',
  extended: true,
  parameterLimit:50000
}));

回答by user1709076

2016, none of the above worked for me until i explicity set the 'type' in addition to the 'limit' for bodyparser, example:

2016 年,在我明确设置了 bodyparser 的“限制”之外的“类型”之前,上述所有内容都不适合我,例如:

  var app = express();
  var jsonParser       = bodyParser.json({limit:1024*1024*20, type:'application/json'});
  var urlencodedParser = bodyParser.urlencoded({ extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoded' })

  app.use(jsonParser);
  app.use(urlencodedParser);

回答by Vivek22

The following worked for me... Just use

以下对我有用......只需使用

app.use(bodyParser({limit: '50mb'}));

that's it.

就是这样。

Tried all above and none worked. Found that even though we use like the following,

以上都试过了,都没有用。发现即使我们使用如下,

app.use(bodyParser());
app.use(bodyParser({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb'}));

only the 1st app.use(bodyParser());one gets defined and the latter two lines were ignored.

只有第一行app.use(bodyParser());被定义,后两行被忽略。

Refer: https://github.com/expressjs/body-parser/issues/176>> see 'dougwilson commented on Jun 17, 2016'

请参阅:https: //github.com/expressjs/body-parser/issues/176>> 参见“dougwilson 于 2016 年 6 月 17 日发表的评论”

回答by Stenal P Jolly

For express ~4.16.0, express.json with limit works directly

对于 express ~4.16.0,带有限制的 express.json 直接工作

app.use(express.json({limit: '50mb'}));

回答by Jaime Fernandez

In my case the problem was on Nginx configuration. To solve it I have to edit the file: /etc/nginx/nginx.confand add this line inside server block:

就我而言,问题出在Nginx 配置上。为了解决它,我必须编辑文件:/etc/nginx/nginx.conf并在服务器块中添加这一行:

client_max_body_size 5M;

Restart Nginx and the problems its gone

重启 Nginx 问题就解决了

sudo systemctl restart nginx

回答by Alexander Sasha Shcherbakov

Little old post but I had the same problem

小旧帖子,但我遇到了同样的问题

Using express 4.+ my code looks like this and it works great after two days of extensive testing.

使用 express 4.+ 我的代码看起来像这样,经过两天的广泛测试后效果很好。

var url         = require('url'),
    homePath    = __dirname + '/../',
    apiV1       = require(homePath + 'api/v1/start'),
    bodyParser  = require('body-parser').json({limit:'100mb'});

module.exports = function(app){
    app.get('/', function (req, res) {
        res.render( homePath + 'public/template/index');
    });

    app.get('/api/v1/', function (req, res) {
        var query = url.parse(req.url).query;
        if ( !query ) {
            res.redirect('/');
        }
        apiV1( 'GET', query, function (response) {
            res.json(response);
        });
    });

    app.get('*', function (req,res) {
        res.redirect('/');
    });

    app.post('/api/v1/', bodyParser, function (req, res) {
        if ( !req.body ) {
            res.json({
                status: 'error',
                response: 'No data to parse'
            });
        }
        apiV1( 'POST', req.body, function (response) {
            res.json(response);
        });
    });
};