Categories
express node.js path

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
});