使用 node.js 重写 url 路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13446030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rewrite url path using node.js
提问by Rafael Motta
Is it possible to rewrite the URL path using node.js?(I'm also using Express 3.0)
是否可以使用 node.js 重写 URL 路径?(我也在使用 Express 3.0)
I've tried something like this:
我试过这样的事情:
req.url = 'foo';
But the url continues the same
但网址继续相同
回答by David Weldon
Sure, just add a middleware function to modify it. For example:
当然,只需添加一个中间件功能来修改它。例如:
app.use(function(req, res, next) {
if (req.url.slice(-1) === '/') {
req.url = req.url.slice(0, -1);
}
next();
});
This function removes the trailing slash from all incoming request URLs. Note that in order for this to work, you will need to place it before the call to app.use(app.router).
此函数从所有传入的请求 URL 中删除尾部斜杠。请注意,为了使其工作,您需要将其放置在调用app.use(app.router).
回答by Tiago Gouvêa
A good idea should be to update the pathtoo. My method suggestions:
一个好主意应该是更新path太。我的方法建议:
app.use(function(req, res, next) {
console.log("request", req.originalUrl);
const removeOnRoutes = '/not-wanted-route-part';
req.originalUrl = req.originalUrl.replace(removeOnRoutes,'');
req.path = req.path.replace(removeOnRoutes,'');
return next();
});
By this way /not-wanted-route-part/userswill became /users
这样/not-wanted-route-part/users就会变成/users

