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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9049993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:06:06  来源:igfitidea点击:

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

node.jsfile-uploadsizeexpresshttp-request

提问by murvinlai

I'm using Node.js and express.

我正在使用 Node.js 和 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 right away. I looked at the code and I think if I change the core, I can do it. However, is there a way to set a max_request_sizeor soemthing like that?

我想限制 HTTP 请求的大小。假设有人向我发送超过 2 MB 的 HTTP 请求,我会立即停止该请求。我查看了代码,我认为如果我更改核心,我可以做到。但是,有没有办法设置max_request_size类似的东西?

It is kind of related to my second question. I'm using express to get an uploaded file from req.files. Is there a way to stop writing the file to the /tmpfolder (which is the default upload behavior) as soon as the file size exceeds a certain file size?

这与我的第二个问题有关。我正在使用 express 从req.files. /tmp一旦文件大小超过某个文件大小,有没有办法停止将文件写入文件夹(这是默认上传行为)?

回答by Gaston

Just an update (07-2014), as I'm not able to add comments:

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

As correctly noted above, newer Express versions have deprecated the use of the limitmiddleware and now provide it as a built-in optionfor the BodyParsermiddleware:

如上所述,较新的 Express 版本已弃用limit中间件,现在将其作为中间件的内置选项提供BodyParser

   var express    = require('express')
   var bodyParser = require('body-parser')

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

回答by AJS

Source code of node github :

节点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=<value>). 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

因此,您需要从源头重建节点以超过 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).

您可以在 Express 4 中使用它来限制请求正文大小/上传文件大小,而不是 express.json() 和 express.urlencoded(),您必须需要 body-parser 模块并使用其 json() 和 urlencoded() 方法, 如果没有为 bodyParser.urlencoded() 显式定义扩展选项,则会抛出警告(body-parser deprecated undefined extended:提供扩展选项)。

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

回答by Rohan Singh

Express uses Connect, which has a limit middleware available. You can use this in your Express app by doing something like this:

Express 使用 Connect,它具有有限的可用中间件。您可以通过执行以下操作在您的 Express 应用程序中使用它:

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

That, for example, would limit all HTTP requests to 2 MB. Since uploaded files are part of the HTTP request, any file upload larger than 2 MB would be aborted as well.

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



NOTE:This middleware is deprecated and will soon be removed. Discussion on why this is the case is available at: https://github.com/senchalabs/connect/pull/925#issuecomment-26990726

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

回答by Wakahiu Njenga

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

使用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)
        })
    })
  • Remember to add the router after the app.use
  • 记得添加路由器后 app.use

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

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

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

回答by SUNDARRAJAN K

Answer for Question 1:

问题 1 的答案

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

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

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

bodyParser.urlencoded

bodyParser.urlencoded

The files from the front end comes as urlencoded bodies.

来自前端的文件以 urlencoded 正文的形式出现。

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.

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

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).

包含解析数据的新主体对象填充在中间件之后的请求对象上(即 req.body)。该对象将包含键值对,其中值可以是字符串或数组(当扩展为假时)或任何类型(当扩展为真时)。

bodyParser.json

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.

返回只解析 json 的中间件。此解析器接受正文的任何​​ Unicode 编码,并支持 gzip 和 deflate 编码的自动膨胀。

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

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

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

注意:默认情况下,正文解析器的输入限制是100kb

Answer for Question 2:

问题 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.

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

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

Reference:

参考

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

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

Hope this helps!

希望这可以帮助!

回答by elarctheitroadis

For an updated solution that isn't deprecated, you can add the limit like so, in your app.js file:

对于未弃用的更新解决方案,您可以像这样在 app.js 文件中添加限制:

app.use(express.json({limit: '2mb'}));
app.use(express.urlencoded({limit: '2mb', extended: false}));

You can also do it like this:

你也可以这样做:

app.use(express.json({limit: 2000000}));
app.use(express.urlencoded({limit: 2000000, extended: false}));

回答by kk4You

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