[Solved-3 Solutions] Error: request entity too large
Error Description:
- We receive the following error with express:
Solution 1:
- setting
app.use(express.bodyParser({limit: '50mb'}));
does set the limit correctly. - When adding a
console.log('Limit file size:'+limit);
- In ,
node_modules/express/node_modules/connect/lib/middleware/json.js:46
and restarting node, we get this output in the console:
- We can see that at first, when loading the
connect
module, the limit is set to 1mb (1048576 bytes). Then when we set the limit, theconsole.log
is called again and this time the limit is 52428800 (50mb). However, we still get a413 Request entity too large.
- Then added
console.log('Limit file size: '+limit);
innode_modules/express/node_modules/connect/node_modules/raw-body/index.js:10
and saw another line in the console when calling the route with a big request (before the error output) :
- This means that somehow, somewhere,
connect
resets the limit parameter and ignores what we specified. I tried specifying thebodyParser
parameters in the route definition individually, but no luck either.
- 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 :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 a bad practice and will be overwritten if you update your module.
- 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 Github about this problem.
Solution 2:
- 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 wasexpress.json().
- Moving
bodyParser
above it did the trick. - That said, the
bodyParser
method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitely, like so :
- In case you need multipart (for file uploads) see this post.
Solution 3:
- Note that in Express 4, instead of
express.json()
andexpress.urlencoded(),
you must require the body-parser module and use itsjson()
andurlencoded()
methods, like so :
- If the
extended
option is not explicitly defined forbodyParser.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 not be optional anymore. For more info on the extended option, please refer to the readme of body-parser.