微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 如何在Express JS 4中进行URL重写

我正在尝试在Express JS 4中进行URL重写.我读到的所有内容都说我应该能够覆盖中间件中的request.url属性.重写的两个现有Node模块使用此方法.但是,当我尝试这样做时:

app.use('/foo',function(req,res){
    var old_url = req.url;
    req.url = '/bar';

    console.log('foo: ' + old_url + ' -> ' + req.url);
});

app.get('/bar',res) {
    console.log('bar: ' + req.url);
});

它只是不起作用.

一个可能有用的注释:看起来上面的req.url总是/不管实际使用的URL. Express 4是否更改了URL的维护方式,而不是更新文档?如何在Express 4中完成URL重写?

解决方法

如果您希望在更改后继续处理,则必须在中间件中调用next()以使处理继续进行其他处理程序.

app.use('/foo',res,next){
    var old_url = req.url;
    req.url = '/bar';

    console.log('foo: ' + old_url + ' -> ' + req.url);
    next();
});

doc for req.originalUrl说:

This property is much like req.url; however,it retains the original
request URL,allowing you to rewrite req.url freely for internal
routing purposes. For example,the “mounting” feature of app.use()
will rewrite req.url to strip the mount point.

这肯定意味着您可以更改req.url以更改路由.

相关回答:Rewrite url path using node.js

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐