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