Miquel
Miquel

Reputation: 8969

Express 4 parameter condition

I would like to have the following routes:

// Services without csrf()
router.get('/user/:uid', userRes.findUser, userRes.GETUser);
router.post('/user/:uid', userRes.findUser, userRes.POSTUser);

// Rest of routes, with csrf()
router.use(csrf());

router.post('/user/subscribe', indexRes.POSTSubscribe);

But what happens here is that POST /user/subscribe is matching second route.

I've been reading Express routes parameter conditions but it shows how to filter numbers. I would like to filter 'subscribe' path:

Is there any chance?

Upvotes: 1

Views: 323

Answers (2)

David
David

Reputation: 2761

You could use router.param:

var staticUserPaths = ['subscribe'];
router.param('uid', function (req, res, next, id) {
  if (~staticUserPaths.indexOf(id)) {
    next('route');
  } else {
    next();
  }
});

Upvotes: 1

mscdex
mscdex

Reputation: 106696

If you move your /user/subscribe route before the /user/:uid route, it will get executed instead of the /user/:uid route for requests to /user/subscribe. Routes/middleware in Express are executed in the order they are attached.

Upvotes: 1

Related Questions