d-_-b
d-_-b

Reputation: 4522

Express: How to properly define routes?

Suppose I have two routes defined like the following.
The first route is always executed, but the second one is not.
How should I define the routes, so that requests for /about.. are properly routed?

// First route
router.get('/:id', function (req, res) {
  // This will always be executed
})

// Second route
router.get('/about/:name', function (req, res) {
  // This will not be executed
})

Upvotes: 1

Views: 64

Answers (1)

Usman Mutawakil
Usman Mutawakil

Reputation: 5259

Reverse the order

The routes are stored in a sequence in the order of your router.get() function calls. That is the order the routes are tested for a matching pattern. When you have a route that matches potentially everything, like an /:Id route, then you want to place it last. You then place the static non-changing ancillary pages before it.

In the example below I reverse the order so my static less specific route of "/about/" is checked first and if there is no match then express will compare the request to the next route for a URL match.

// Executed if match is found
router.get('/about/:name', function (req, res) {
})

// No match found on the above routes so try this one
router.get('/:id', function (req, res) {
})

//TODO: Good place for 404 handler...

Upvotes: 1

Related Questions