简体   繁体   中英

Express.js: Match route in catch all

Can one check a express.js route against multiple patterns? Consider the catch all * route below. req.route is matched to * here. I'd like to check the route against a few special scenarios within the same callback ~ NOT inside another all or use middleware.

app.all('*', (req, res, next) => {
  // How do I check if route is a special case like below
  if(req.route in ['/foo/:param', '/bar/:param']){}
})

I'm not sure why you're dismissing separate .all routes for this, because it seems to me to be the best way of performing these checks:

app.all('/foo/:param', (req, res, next) => {
  req.isFoo = true;
  next();
});

app.all('/bar/:param', (req, res, next) => {
  req.isBar = true;
  next();
});

app.all('*', (req, res, next) => {
  if (req.isFoo || req.isBar) { ... }
})

Or, analogous to Chris's answer, have one route to match both:

app.all([ '/foo/:param', '/bar/:param' ], (req, res, next) => {
  req.isSpecial = true;
  next();
});

So you should not try to use the wildcard to capture everything than look for specific values. Instead, create an endpoint that looks for these specific values and then use another route for the capture all wildcard.

app.get(['/test', '/another_value'], (req, res, next) => {

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM