Reputation: 4436
I have a NodeJS web application. I disseminated one route with this text:
great impact (learn more at emotionathletes.org/impact)
The route /impact
exists, the route /impact)
does not. Some email clients include the closing parenthesis in the route and I would like to redirect it. If I use:
router.get("/impact)", (req, res) => {
res.redirect("/impact");
});
I get this error:
~/emotionathletes/server/node_modules/path-to-regexp/index.js:128
return new RegExp(path, flags);
^
SyntaxError: Invalid regular expression: /^\/impact)\/?$/: Unmatched ')'
I understand that route strings serve as input to regular expressions, where parentheses serve to catch groups, and thus cannot contain parenthesis. Using HTML entities such as /impact%29
does not catch the route /impact)
.
One solution is a generic handler such as:
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.
// ...
}
What is the proper way to catch routes with parentheses in NodeJS?
Upvotes: 1
Views: 683
Reputation: 5692
Try to use unicode expression [ \u0029 = )
] with regex
router.get(/impact\u0029/, (req, res) => { ... }
I think your second approach is more appropriate if you have multiple routes having the same issue. If there is only one route, then you can use the above solution.
Upvotes: 1