【问题标题】:Catching route with parentheses in the path在路径中用括号捕获路径
【发布时间】:2021-05-18 09:15:43
【问题描述】:

我有一个 NodeJS 网络应用程序。我用这段文字传播了一条路线:

great impact (learn more at emotionathletes.org/impact)

路由/impact存在,路由/impact)不存在。一些电子邮件客户端在路由中包含右括号,我想重定向它。如果我使用:

router.get("/impact)", (req, res) => {
  res.redirect("/impact");
});

我收到此错误:

~/emotionathletes/server/node_modules/path-to-regexp/index.js:128
  return new RegExp(path, flags);
         ^

SyntaxError: Invalid regular expression: /^\/impact)\/?$/: Unmatched ')'

我了解路由字符串用作正则表达式的输入,其中括号用于捕获组,因此不能包含括号。使用 /impact%29 等 HTML 实体不会捕获路由 /impact)

一种解决方案是通用处理程序,例如:

router.get("/:token", async (req, res, next) => {

  // Remove parenthesis in the route path.
  let newPath = req.originalUrl.replace(")", "").replace("(", "");
  if (newPath != req.originalUrl) {
    return res.redirect(newPath);
  }

  // Any other routes, such as 404.
  // ...
}

在 NodeJS 中用括号捕获路由的正确方法是什么?

【问题讨论】:

  • 看起来很丑,试试 `"/login\\)"``
  • 是的,这行得通,你能写一个答案吗?

标签: node.js regex express url-routing


【解决方案1】:

尝试在正则表达式中使用 unicode 表达式 [ \u0029 = )]

router.get(/impact\u0029/, (req, res) => { ... }

我认为如果您有多条路线都有相同的问题,您的第二种方法更合适。如果只有一条路线,则可以使用上述方案。

【讨论】:

  • 我接受了这个答案,因为它在路由中提到了正则表达式。
猜你喜欢
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-05
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多