Express Route Regex Match With Question Mark

Viewed 780

I've been trying to match the following URL:

http://localhost:3000/?uid=Nf83K3L

with app.get(/^\/\?uid.+/, userController.redirectUid) but it's not working.

I've tried to escape the question mark with \? as well, but still doesn't work. Am I doing something wrong, or am I not allowed to match question marks in express routes?

2 Answers

You don't need the carat(^) as it means / should be the beginning of the string you want to match.

app.get(/\/\?uid.+/, userController.redirectUid).

Hope this fixes your issue.

I'm not sure why app.get didn't work, but managed to solve it with app.use and matching it to the req.OriginalUrl.

Working code:

app.use((req, res, next) => {
  if (req.originalUrl.match(/^\/\?uid.+/)) {
    res.redirect('/uid') //I just redirected directly without calling the middleware
  }
}
Related