mur*_*lai 17 size file-upload node.js http-request express
我正在使用Node.js并表达.
我想限制HTTP请求的大小.假设有人向我发送超过2 MB的HTTP请求,那么我立即停止请求.我查看了代码,我想如果我改变核心,我就可以做到.但是,有没有办法设置max_request_size这样的东西?
这与我的第二个问题有关.我正在使用express来获取上传的文件req.files./tmp一旦文件大小超过某个文件大小,有没有办法停止将文件写入文件夹(这是默认的上载行为)?
Gas*_*ton 18
只是一个更新(07-2014),因为我无法添加评论:
如上所述,较新的Express版本已弃用limit中间件,现在将其作为中间件的内置选项提供BodyParser:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json({ limit: '5mb' }))
Run Code Online (Sandbox Code Playgroud)
Roh*_*ngh 10
Express使用Connect,它具有可用的限制中间件.您可以通过执行以下操作在Express应用中使用此功能:
app.use(express.limit('2mb'));
Run Code Online (Sandbox Code Playgroud)
例如,这会将所有HTTP请求限制为2 MB.由于上传的文件是HTTP请求的一部分,因此任何大于2 MB的文件上传也将被中止.
注意:此中间件已弃用,很快将被删除.有关原因的讨论,请访问: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 (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
Run Code Online (Sandbox Code Playgroud)
因此,您需要从源重建节点超过80*1024的限制
你可以使用Express 4来限制请求体大小/上传文件大小,而不是express.json()和express.urlencoded(),你必须要求body-parser模块并使用它的json()和urlencoded()方法,如果没有为bodyParser.urlencoded()显式定义扩展选项,它将抛出一个警告(body-parser不推荐使用undefined extended:提供扩展选项).
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
Run Code Online (Sandbox Code Playgroud)
对于未弃用的更新解决方案,您可以在 app.js 文件中添加限制,如下所示:
app.use(express.json({limit: '2mb'}));
app.use(express.urlencoded({limit: '2mb', extended: false}));
Run Code Online (Sandbox Code Playgroud)
你也可以这样做:
app.use(express.json({limit: 2000000}));
app.use(express.urlencoded({limit: 2000000, extended: false}));
Run Code Online (Sandbox Code Playgroud)