Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining path in Express router routes

I've set up an express app and using the routing middleware to abstract some routes into a separate include.

I reference them using this style in the app.js:

app.use('/foo', my_urls);

This means "/foo/bar" in the browser is handled as if it's "/bar".

The problem though is that in the router.get("/bar"...) section in the included router file, I need to know the value of the preceding (foo) part. I've set up the route that this "foo" could be anything from an array of values.

Is there any way to know the context of the routing middleware, the preceding part of the path that the routes are acting within? In other words, can I do something like (pretend code here):

router.get('/bar', function(req, res, next) {
  res.send(req.path[0]) // foo
});

Solved: Thanks for the answer. I can get the value using this:

router.get('/bar', function(req, res, next) {
  res.send(req.baseUrl.splice(1)) // foo
});
like image 910
Don H Avatar asked Jan 07 '16 09:01

Don H


1 Answers

express has req.path property so you can know the path but is shows path after parent Router's path (if you have one), so to get parent router path you can use req.baseUrl and req.originalUrl to get full url with queryparam.

like image 82
Bek Avatar answered Oct 28 '22 06:10

Bek