'How to get the full URL of an express request, with placeholders as-is?
I am using express.Router instances create routes and bind them to base routes with app.use(), and I use placeholders in those routes to populate the req.params object. A complete route might look like /user/:id/profile -- I'm looking for the way to get that /user/:id/profile string.
Here's an example server:
const express = require('express');
const router = express.Router({ mergeParams: true });
const app = express();
router.get('/profile', (req, res) => {
console.log(req.url); // prints "/profile"
console.log(req.baseUrl); // prints "/user/foo"
console.log(req.originalUrl); // prints "/user/foo/profile"
console.log(req.route.path); // prints "/profile"
res.send(`hello ${req.params.id}`);
});
app.use('/user/:id', router);
app.listen(49500, () => {
console.log('listening');
});
curl localhost:49500/user/foo/profile returns hello foo and logs the values shown above in the example script, but nothing I've found gives me /user/:id/profile, and I've checked req and res.
There have been similar questions posted to SO, but the key difference here is I am looking for a way to preserve the placeholders.
Edited to add: I'm running express 4.17.2 (latest version at the time of this post) in node 17.0.1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
