I have the code
app.get('/(new)?', (req, res) => {}
Express returns a SyntaxError: Invalid regular expression: /^\/(?(?:([^\/] ?)))?\/?$/: Invalid group
I did a little of Troubleshooting and found out that the problem is somehow between the slash and brace. If I do app.get('/e(new)?', (req, res) => {}
it works just fine...
How can I get around this? Why does this occur? Please don't hate me for anything stupid I might have done or not finding something on it...
I am using Express 4.17.1.
CodePudding user response:
Use a RegExp literal instead of encapsulating it in a string:
app.get(/\/(new)?/, (req, res) => {}
It's tough to say exactly why this works over what you had originally, but my best guess is that there you've hit a small edge case in the way that these faux-RegExp patterns are interpreted in Express' route signature parser that is not triggered when expressing the pattern literally this way.
If you're so inclined, you may consider reporting this as an issue in Express' GitHub repository - some of the more involved contributors may be able to pinpoint exactly where in the codebase this pattern causes issues.