Node.js:如何限制HTTP请求的大小和上传文件大小?

我使用Node.js并表示。

我想限制HTTP请求的大小。 比方说,如果有人向我发送超过2MB的HTTP请求,我立即停止请求。 我看了代码,我想如果我改变核心,我可以做到这一点。 但是,有没有办法设置max_request_size或类似的东西呢?

这与我的第二个问题有关。 我使用快递从req.files获取上传的文件。 如果文件大小超过某个文件大小,是否有办法停止将文件写入/tmp文件夹(这是默认的上传行为)?

只是一个更新(07-2014),因为我无法添加评论:

正如上面正确指出的,较新的Express版本已经不再使用limit中间件,现在将其作为BodyParser中间件的内置选项提供:

  var express = require('express') var bodyParser = require('body-parser') var app = express() app.use(bodyParser.json({ limit: '5mb' })) 

Express使用连接,它具有可用的中间件限制 。 您可以在Express应用程序中使用这样的操作:

 app.use(express.limit('2mb')); 

例如,这会将所有HTTP请求限制为2 MB。 由于上传的文件是HTTP请求的一部分,所以大于2MB的file upload也将被中止。


注意:此中间件已弃用,将很快被删除。 有关这种情况的讨论,请访问: https : //github.com/senchalabs/connect/pull/925#issuecomment-26990726

节点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 (eg -DHTTP_MAX_HEADER_SIZE=<value>). To remove * the effective limit on the size of the header, define the macro * to a very large number (eg -DHTTP_MAX_HEADER_SIZE=0x7fffffff) */ #ifndef HTTP_MAX_HEADER_SIZE # define HTTP_MAX_HEADER_SIZE (80*1024) #endif 

所以,你需要从源码重build节点超过80 * 1024的限制

您可以使用Express 4来限制请求正文大小/上传文件大小,而不是express.json()和express.urlencoded(),您必须要求body-parser模块并使用其json()和urlencoded()方法如果扩展选项没有为bodyParser.urlencoded()显式定义,它将会抛出一个警告(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})); 

使用raw-body 。 大多数中间件(如限制)不再与Express捆绑在一起,必须单独安装。 这是一个例子。

 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) }) }) 
  • 请记住在app.use之后添加路由器

Express不再允许您使用传统的捆绑中间件明确设置限制,如下所示。

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

问题1的答案

要限制HTTP请求大小和上传文件大小,我们需要设置body-parser限制。

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

bodyParser.urlencoded

来自前端的文件来自urlencoded的机构。

返回仅parsingurlencoded主体的中间件。 此parsing器只接受身体的UTF-8编码,并支持gzip和deflate编码的自动膨胀。

在中间件之后的请求对象(即req.body)上填充包含parsing的数据的新的主体对象。 该对象将包含键值对,其中值可以是string或数组(当扩展为false时)或任何types(当扩展为true时)。

bodyParser.json

返回只parsingjson的中间件。 这个parsing器接受身体的任何Unicode编码,并支持gzip和deflate编码的自动膨胀。

在中间件之后的请求对象(即req.body)上填充包含parsing的数据的新的主体对象。

注意 :默认情况下,正文parsing器的input限制是100kb

问题2的答案

要更改默认的上传目录,我们可以使用以下内容。

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

其他实施

在将bodyParser包含到应用程序中的同时,我们可以提及上传目录。

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

参考

问题 : https : //github.com/expressjs/express/issues/1684

希望这可以帮助!