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

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

    Use raw-body. Most middleware (like limit) is no longer bundled with Express and must be installed separately. Here's an example.

    var getRawBody = require('raw-body')
    app.use(function (req, res, next) {
          getRawBody(
            stream = req,
            options = {
              length: req.headers['content-length'],
              limit: '100mb',
            },
            callback = function (err, reslt) {
              if (err) {
                return next(err)
              }
              next();
              console.log(req)
            })
        })
    
    • Remember to add the router after the app.use

    Express no longer allows you to explicitly set the limit using the traditional bundled middleware as show below.

    app.use(express.limit('4M'));
    

提交回复
热议问题