My code example:
router.get('/name/:name/height', (req,res) => {
...
}
router.get('/name/:name/weight', (req,res) => {
...
}
router.get('/age/:age/height', (req,res) => {
...
}
router.get('/age/:age/weight', (req,res) => {
...
}
Here, when name comes as foo, I want to replace it to bar because foo is an alias of bar.
But inserting if-replace codes into all the blocks repeatedly doesn’t look good.
Is there any other option to implement this??
I tried with:
router.use('/name/:name', (req, res, next) => {
let name = req.params.name
if (name === 'foo') {
console.log("HHHHHHHHHHHHHHHHHHH")
req.params.name = 'bar'
}
next()
}
)
That HHH... log is printed, but the req.params.name doesn’t seem to be updated.
Advertisement
Answer
If foo is indeed an alias for bar, I’d suggest you respond with a 301 Redirect response for the foo endpoint with something like this:
router.get('/name/foo/:path', (req, res) => {
res.redirect(301, '/name/bar/' + req.path);
});