1

I'm trying to create an authentication mechanism for my app by checking cookies. So I added the router.all('*') to match every request, check the cookie, and then go to the actual handler. But I need it to only match requests which have one or more characters after '/'. (I want to match /manage, /m or /about, but not /).

//Assuming a request for '/', this gets called first
router.all('*', function (request, response, next) {
    //Stuff happening
    next();
});

//This gets called on next(), which I do not want
router.get('/', function (request, response) {
    //Stuff happening
});

//However this I do want to be matched when requested and therefore called after router.all()
router.post('/about', function (request, response) {
    //Stuff happening
});

According to the answers here you can use regex for path matching but then I don't really understand what '*' is. It might match everything, but it doesn't look like regex to me.

  1. Why does '*' match /?
  2. What argument do I need to suplly to all() to match /about but not /?
Community
  • 1
  • 1
iuliu.net
  • 6,666
  • 6
  • 46
  • 69

2 Answers2

3

Simply put * last. The router checks in order of definition.

So:

router.get('/' ...

then

router.all('*' ...

Just remember that / is still valid for *, so a next() call from / will trigger the catch all process.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • 1
    Sometimes the solution to your problem is not the answer to your question, but the solution to the problem. – iuliu.net May 22 '16 at 11:48
1

A path that consists of just the star character ('*') means "match anything", which includes just the hostname on its own.

In order to only "match something" use the dot group with the plus operator, which means "match anything at least once".

router.all(/\/^.+$/, () => {
  // ...
})
sdgluck
  • 24,894
  • 8
  • 75
  • 90