0

I would like to prevent any (or particular) requests larger than set size.

Example: 1GB POST request. Limit - 5MB. The upload starts and once it hits 5MB, the server immediately flushes the memory, withdraws the request and sends an error back.

Is there any good mechanism to do it?

Edit: I use multipart requests.

Duplicate: How to limit upload file size in express.js

Community
  • 1
  • 1
igorpavlov
  • 3,196
  • 5
  • 25
  • 50
  • Possible duplicate of [How to limit upload file size in express.js](http://stackoverflow.com/questions/13374238/how-to-limit-upload-file-size-in-express-js) – igorpavlov Oct 24 '15 at 15:38

1 Answers1

1

You can use body parser:

var bParser = require('body-parser');

app.use(bParser.json({limit: '5mb'}));
app.use(bParser.urlencoded({limit: '5mb'}));

doc: https://www.npmjs.com/package/body-parser#limit

Pavel Durov
  • 1,204
  • 2
  • 11
  • 25
  • Just edited my question. This parser says "This does not handle multipart bodies, due to their complex and typically large nature." – igorpavlov Oct 24 '15 at 14:51
  • Is there any simple way to do without heavy modules such as busboy? – igorpavlov Oct 24 '15 at 14:53
  • Can't you check then the request.headers.content-length value in your onRequest event? – Pavel Durov Oct 24 '15 at 15:05
  • Is this secure? Can't malicious users just type whatever they want in content.length or send the data in chunks? – igorpavlov Oct 24 '15 at 15:07
  • No it's not secure at all, you will need to check the actual body byte size eventually. – Pavel Durov Oct 24 '15 at 15:08
  • Exactly, how can I do it during the upload then? :) – igorpavlov Oct 24 '15 at 15:09
  • expressjs is an open source, take a look at their GitHub repository: https://github.com/expressjs/body-parser/blob/7847af6e5a36129eea0e0becfbcc521b839313ae/lib/types/json.js – Pavel Durov Oct 24 '15 at 15:10
  • 1
    What exactly are you doing after the request with the body data? – Pavel Durov Oct 24 '15 at 15:15
  • Does that actually matter in this case? Let's say I do nothing, just send an empty JSON back. – igorpavlov Oct 24 '15 at 15:17
  • 1
    Well, it really can matter what are your doing, for instance if you are opening a stream with a client and read the data by chunks, you can stop the process as you reach the limit - I am not really telling you to do so, I'm just saying that custom modifications usually relies on specific implementation. – Pavel Durov Oct 25 '15 at 14:16