Reputation: 1679
I'm building a middleware to check acl, but I cannot find a way to get the URL of dynamic routes. Example : '/user/:id/movie/:name'. I'm able to get the url but it's already filled with the id and name, how can I get the raw URL for this dynamic routes ? (I already checked baseUrl, originalUrl, url)
Upvotes: 0
Views: 1164
Reputation: 2531
So express doesn't know what is the end dynamic URL due to router
. Each route can be appended to any URL prefix.
in your case:
user/:id
- is the prefixmovie/:name
- is the routeconst express = require('express')
const app = express()
const port = 3000
// add empty urlTemplate on each incoming request
app.use((req, res, next) => {
req.urlTemplate = "";
next();
});
// create route
var router = express.Router()
const urlTemplateMove = '/movie/:name';
const moveRoute = router.get(urlTemplateMove, function (req, res) {
req.urlTemplate += urlTemplateMove; // <- append current route urlTemplate
console.log(req.urlTemplate);
res.json(req.urlTemplate);
});
// append urlTemplate on each route
const urlTemplateUser = '/user/:id';
app.use(urlTemplateUser, (req, res, next) => {
req.urlTemplate += urlTemplateUser;
moveRoute(req, res, next);
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
Note if you're not interested in using router
you just create the URL as in a higher scope and then you will have access to it in the callback.
const express = require('express')
const app = express()
const port = 3000
const urlTemplate = '/user/:id/movie/:name';
app.get(urlTemplate, function (req, res) {
console.log(urlTemplate);
res.json(urlTemplate);
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
Upvotes: 3