【问题标题】:Disable/Override bodyparser behaviour禁用/覆盖 bodyparser 行为
【发布时间】:2019-05-24 07:38:33
【问题描述】:

我们可以在将bodyparser作为中间件注入后禁用或覆盖它来表达应用程序吗?

在一个文件中(不可编辑,由框架完成) app.use(bodyParser.json()); 导出应用程序;

在其他文件中,我正在导入应用程序,在这里我想为其中一条路线禁用 bodyParser。有什么办法可以做到吗?

【问题讨论】:

    标签: node.js express middleware body-parser


    【解决方案1】:
    // export file
    // ...
    
    app.use((req, res, next) => {
      // check if the path need body parser or not
      if (BlackList.includes(req.path)) {
        bodyParser.json()
      }
      next()
    });
    
    // ...
    
    // import file
    // ...
    
    // some router
    BlackList.push('anyway')
    app.get('/anyway', function (req, res, next) {
      // your code...
    })
    
    // ...
    

    【讨论】:

    • 我同意,但有没有其他方法可以在没有任何额外变量的情况下取消/删除 bodyParser 行为?我的意思是在将其作为 app.use(bodyParser); 之类的中间件注入之后app.use(删除 bodyParser);
    • 像 node http Server 一样,我们可以移除附加到它的监听器。 server.removeListener(.....)
    猜你喜欢
    • 2021-09-06
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2019-11-28
    相关资源
    最近更新 更多