Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the mount path of router on express?

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
});
like image 648
Antón Molleda Avatar asked Jun 12 '15 18:06

Antón Molleda


People also ask

What is Mount path in Express?

The app. mountpath property contains those path patterns on which a sub-app was mounted. A sub-app can be defined as an instance of Express that may be used for handling the request to a route.

What is router route in node JS?

What is routing? To start with routing in Node. js, one needs to know what is routing and its purpose. The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern.

What are Route parameters in Express?

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req. params object, with the name of the route parameter specified in the path as their respective keys.

How routing is working in Express?

In express 4, multiple routes can be assigned to a router, and then to use the router, the router is given a root path and placed in the "middleware" stack via app. use(path, router). This allows related routes to each use their own router and to be assigned a base path as a unit.


1 Answers

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>

like image 130
stdob-- Avatar answered Oct 20 '22 18:10

stdob--