【问题标题】:How do I set the bodyParser upload limit to specific routes rather than globally in the middleware?如何在中间件中将 bodyParser 上传限制设置为特定路由而不是全局?
【发布时间】:2013-09-27 20:16:33
【问题描述】:

这是一个在全球范围内为我工作的示例 (Express 3) 中间件设置:

app.configure(function () {
    app.use(express.static(__dirname + "/public"));
    app.use(express.bodyParser({
          keepExtensions: true,
          limit: 10000000, // set 10MB limit
          defer: true              
    }));
    //... more config stuff
}

对于security reasons,我不想在/upload 以外的路由上允许500GB+ 的帖子,所以我试图弄清楚如何在特定路由上指定限制,而不是在中间件中全局指定限制。

我知道multipart middleware in bodyParser() 已经嗅出内容类型,但我想进一步限制它。

这似乎在 express 3 中不起作用:

app.use('/', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 10,
  defer: true              
}));
app.use('/upload', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 1024 * 500,
  defer: true              
}));

当我尝试在 upload URL 上上传 3MB 文件时,我收到错误 Error: Request Entity Too Large

你如何正确地做到这一点?

【问题讨论】:

    标签: node.js express connect large-file-upload


    【解决方案1】:

    使用app.use()时只需指定可选路径选项。

    app.use('/', express.bodyParser({
      keepExtensions: true,
      limit: 1024 * 1024 * 10,
      defer: true              
    }));
    app.use('/upload', express.bodyParser({
      keepExtensions: true,
      limit: 1024 * 1024 * 1024 * 500,
      defer: true              
    }));
    

    【讨论】:

    • 你确定这有效吗?当我尝试上传 3MB 文件时,我收到一条错误消息 Error: Request Entity Too Large,根据您的代码,它应该接受 500GBs
    • 不起作用。不知何故,'defer:true' 给我访问 req.body 带来了问题。
    【解决方案2】:

    实际上正如上面六氰化物所建议的那样,app.use() 用于限制单一路线。
    问题出在路由路径的顺序上。
    回到上面的例子,如果你把'/upload'放在前面,那么bodyParser应该首先匹配那个规则。

    所以把代码写成这样(我用的是Express 4.0 +):

    app.use("/PATH_WITH_LIMIT", bodyParser({ 
        limit: 1024 * 1000
    }));
    app.use("/",bodyParser());
    

    您可以看到 express 如何在 app.use() 方法调用 here 上绑定中间件。

    【讨论】:

    • 我想指出,body 解析器检测是否已经为当前请求解析了 body,并且不进行双重解析。这实际上就是它在这种情况下起作用的原因,否则第二条规则仍然会抛出错误,除非请求会更早结束。
    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多