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

后端 未结 7 1634
轮回少年
轮回少年 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:08

    Source code of node github :

    /* Maximium header size allowed. If the macro is not defined
     * before including this header then the default is used. To
     * change the maximum header size, define the macro in the build
     * environment (e.g. -DHTTP_MAX_HEADER_SIZE=). To remove
     * the effective limit on the size of the header, define the macro
     * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
     */
    #ifndef HTTP_MAX_HEADER_SIZE
    # define HTTP_MAX_HEADER_SIZE (80*1024)
    #endif 
    

    So, you need to rebuild node from source to surpass the limit of 80*1024

    You can use this with Express 4 to limit request body size/Upload file size, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, if the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option).

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

提交回复
热议问题