中间件上的通配符或正则表达式节点表达挂载路径

San*_*ane 5 regex wildcard webhooks node.js express

我想根据路径的外观定义不同的中间件。 在此输入图像描述

问题是道路可能会很谨慎;例如,我想支持以下路径:

/chat/auth/test
/chat/auth/add
/chrome/auth/test
/chrome/add
Run Code Online (Sandbox Code Playgroud)

每次auth位于路径中时,我都希望调用 auth 中间件,对于聊天chrome,我希望调用它们各自的中间件。

应用程序.js:

// Middleware authentication

var chatAuthenticate = require('./server/middleware/chat-authenticate');
app.use('/chat', chatAuthenticate(addon));

var authAuthentication = require('./server/middleware/auth-authenticate');
app.use('/auth', authAuthentication());
Run Code Online (Sandbox Code Playgroud)

我知道我可以为每种可能的组合添加多个条目到 app.js 中,例如 /chat/auth 和 /chrome/auth ,它根本不会增加复杂性,但我只是好奇是否可以解决这与通配符或正则表达式:)

小智 0

app.use(/auth/, authAuthentication);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这将为包含任何位置的每个请求调用 authAuthentication auth。有几点需要考虑:

\n\n
    \n
  • 它是一个正则表达式,因此您只需 /\xe2\x80\xa6/ 作为分隔符而不需要引号
  • \n
  • 请注意,如果您有多个与某个路由匹配的中间件(例如另一个带有/chat/RegEx 的中间件,并且您调用/auth/chat/chat/auth,则两个中间件都会被调用。因此,考虑调用的顺序很重要app.use()
  • \n
  • authAuthentication 需要期望(request, response, next)参数。如果您像示例中那样直接调用该函数,则该函数预计会返回一个采用三个 Express 中间件参数的函数。
  • \n
  • require将所有调用放在脚本的顶部是常见的做法
  • \n
  • 确保您完全阅读并理解Express Routing。太棒了。
  • \n
\n