【问题标题】:Add params on ExpressJS middlewares using regular expressions使用正则表达式在 Express JS 中间件中添加参数
【发布时间】:2015-09-22 15:38:12
【问题描述】:

使用正则表达式时如何将“路径参数”传递给中间件。这是我需要做的一个例子:

app.use(new RegExp('/aPath/(?!notThis){variable}'), myMiddleware);

所以,在我的中间件(不应该为 '/aPath/notThis' 执行)中,我需要获取参数。

exports.myMiddleware = function (req, res, next){
  console.log(req.params.variable);
} 

这可能吗?

【问题讨论】:

    标签: regex node.js express


    【解决方案1】:

    看看this

    app.use(/:variable(?!notThis)/), myMiddleware);
    

    然后在myMiddleware 中,您可以根据需要检查variable 的值。

    【讨论】:

      【解决方案2】:

      您可以使用以下语法将参数传递给中间件:

      var myPath =  require('path')(variable);
      app.use(myPath);
      

      然后在你的中间件中:

      module.exports = function (variable) {
              console.log(variable);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-12
        相关资源
        最近更新 更多