router.post(/^\/(path_A|path_B)/, verify, async (req, res) => {
...
});
The goal is to match the path path_A
and path_B
in the same route. I don't think that the regex is written correctly. Can someone double check?
CodePudding user response:
Your code:
router.post(/^\/(path_A|path_B)/, verify, async (req, res) => {
...
});
Will work just fine to match either /path_A
or /path_B
. I've verified it by running it locally. Some notes on this:
The
^
is required if you want to ensure your regex starts at the beginning of the path and cannot match only something in the middle of the path. For example, without the^
, it would match/X/path_A
or/www/path_B
.Your existing regex will also match
/path_AAAA
and/path_Bxxx
because it does not specify anything after the match. If you only wanted to match just/path_A
or/path_B
with nothing afterwards, then you could put a$
at the end of your regex. These are just regular regexes so they will just match what any old regex would match. All the normal regex rules apply.If you specify a string instead of a regex, then your matching options are more limited (to a subset of regex stuff that the path to regex library supports and Express will require more complete matches by testing for additional conditions. But, if you use a regex object, then all of that is up to you.
FYI, I tried going without the native regex object like this and letting the built-in path-to-regexp handle the details:
router.post("/(path_A|path_B)", verify, async (req, res) => {
...
});
And, it will not work. In fact, it gets a run-time error when executing the router.post()
and parsing the path. In diagnosing the issue, it appears to be an old bug in the path-to-regexp library that has long since been fixed, but Express loads the older version of the library that has this problem. So, for now, what you're trying to do appears to require the full regular expression object.