[英]How can I always replace a certain path parameter to another value in node.js?
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
.在这里,当
name
作为foo
,我想将其替换为bar
因为foo
是bar
的别名。
But inserting if-replace codes into all the blocks repeatedly doesn't look good.但是将 if-replace 代码重复插入所有块看起来并不好。
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.该
HHH...
日志已打印,但 req.params.name 似乎没有更新。
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:如果
foo
确实是bar
的别名,我建议您使用foo
端点的301 Redirect
响应进行响应,如下所示:
router.get('/name/foo/:path', (req, res) => {
res.redirect(301, '/name/bar/' + req.path);
});
Wrap these if-replace codes into a middleware myCustomMiddleware
then put that middleware in any router you need:将这些 if-replace 代码包装到中间件
myCustomMiddleware
然后将该中间件放在您需要的任何路由器中:
const myCustomMiddleware = (req, res, next) => {
let name = req.params.name;
if (name === 'foo') {
req.params.name = 'bar';
}
next();
};
router.get('/name/:name/height', myCustomMiddleware, (req,res) => {
...
});
router.get('/name/:name/weight', myCustomMiddleware, (req,res) => {
...
});
router.get('/age/:age/height', (req,res) => {
...
});
router.get('/age/:age/weight', (req,res) => {
...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.