Node.js: how to limit the HTTP request size and upload file size?

后端 未结 7 1637
轮回少年
轮回少年 2020-12-08 20:35

I\'m using Node.js and express.

I would like to limit the HTTP request size. Let\'s say, if someone sends me a HTTP request more than 2 MB then I stop the request r

7条回答
  •  粉色の甜心
    2020-12-08 21:17

    Answer for Question 1:

    To limit the HTTP request size and upload file size we need to set the body-parser limit.

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

    bodyParser.urlencoded

    The files from the front end comes as urlencoded bodies.

    Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

    A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

    bodyParser.json

    Returns middleware that only parses json. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

    A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).

    Note: By default the input limit for body parser is 100kb

    Answer for Question 2:

    To change the default upload directory we can use the following.

    app.set('uploadDir', './files');  // Sets the upload Directory to files folder in your project.
    

    Other Implementation

    While including the bodyParser into the app we can mention the upload directory.

    app.use(express.bodyParser({uploadDir:'./files', keepExtensions: true}));
    

    Reference:

    • https://github.com/expressjs/body-parser#limit
    • https://github.com/expressjs/body-parser#bodyparserjsonoptions
    • https://github.com/expressjs/body-parser#bodyparserurlencodedoptions

    Issues: https://github.com/expressjs/express/issues/1684

    Hope this helps!

提交回复
热议问题