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
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With