【发布时间】: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