Snorlax
Snorlax

Reputation: 4765

Specifying specific path with Express

I'm having trouble getting my .get() to work. My understanding of .use() vs .get() is that .use() is used for paths we want to apply things to, while .get() is more specific (choosing specific urls to apply to)

In my example, I want to show 'Applies to all pages' to any page number, but if I type in '/28', I want the .get message to show up instead. Right now, I get the .use message even when I go to /28.

router.use('/:id', function(req, res){
   console.log("Things " + Date.now());
   res.send('Applies to all pages ' + req.params.id);

});


router.get('/28', function(req, res){
   res.send('Secret 28 page');
});

Upvotes: 2

Views: 142

Answers (4)

Tolsee
Tolsee

Reputation: 1705

The use method is used to employ all the http verb to certain path from your express app or express router. You have to consider the precedence while using use. Here, what is happening is that you have already employed use in your dynamic router as router.use('/:id', ...) which will take get request as well.

You can employ the get router first, so that it only take getrequest in /28 and transfer all the unhandled request to other path.

router.get('/28', function(req, res){
   res.send('Secret 28 page');
});

router.use('/:id', function(req, res){
   console.log("Things " + Date.now());
   res.send('Applies to all pages ' + req.params.id);

});

Upvotes: 1

animsaj
animsaj

Reputation: 141

.use() applies to all the paths regardless of HTTP verb, so in your case it applies to GET, POST, PUT and all the other requests that start with /:id path and app.get("/28") is such a request

Upvotes: 1

Chris
Chris

Reputation: 993

Try switching the order of your .get and use. ExpressJS goes in sequential order when executing. Read this post for more clarification: https://derickbailey.com/2016/05/09/in-what-order-does-my-express-js-middleware-execute/

Also, a little unrelated but you can use the .get middleware first, and pass the next step using a third parameter to your callback which is next(), if you haven't known that already.

Upvotes: 1

enjoylife
enjoylife

Reputation: 3861

From the docs:

The order in which you define middleware with router.use() is very important. They are invoked sequentially, thus the order defines middleware precedence.

In your example your '/:id' will take precedence when matching.

So swap the order to fix your example, and in general, define more specific handlers first.

Upvotes: 1

Related Questions