How to know the mount path of router on express?

4.7k views Asked by At

I'm using express' Router on a web application. I'm adding the routers the usual way:

app.use(router, '/myroutehere/');

The handlers for each router don't have any idea of where they have been "mounted" (different files, different concerns, etc.). This has worked ok until now that I need to create a ToC for one of the routers (and the content is dynamically generated). I'm using url.resolve to handle the relative paths, but I'm missing the initial part of the url (otherwise the links will resolve to / instead of /myrouter/).

Is there a way to know the mount path of a router without hardcoding it in different places?

router.get('/', function(req, res){
  // Need to know the mount path here or a way to resolve relative links
  // to the mount path and make them absolute to the app
});
1

There are 1 answers

3
stdob-- On BEST ANSWER

What about "router.mountpath"?

The app.mountpath property contains one or more path patterns on which a sub-app was mounted

http://expressjs.com/en/api.html#app.mountpath

Upd. Ok, you need: <req.route.path>, <req.baseUrl>, <req.originalUrl>