I'm using Express JS and I want a functionality similar to Django's reverse
function. So if I have a route, for example
我正在使用Express JS,我想要一个类似于Django的反向功能的功能。所以,如果我有一条路线,例如
app.get('/users/:id/:name', function(req, res) { /* some code */ } )
I'd like to use a function for example
我想用一个函数作为例子
reverse('/users/:id/:name', 15, 'John');
or even better
甚至更好
reverse('/users/:id/:name', { id : 15, name : 'John' });
which will give me the url /users/15/John
. Does such function exist? And if not then do you have any ideas how to write such function (considering Express' routing algorithm)?
这会给我url / users / 15 / John。这样的功能存在吗?如果没有那么你有任何想法如何编写这样的功能(考虑到Express'路由算法)?
2 个解决方案
#1
7
Here is your code:
这是你的代码:
function reverse(url, obj) {
return url.replace(/(\/:\w+\??)/g, function (m, c) {
c=c.replace(/[/:?]/g, '');
return obj[c] ? '/' + obj[c] : "";
});
}
reverse('/users/:id/:name', { id: 15, name: 'John' });
reverse('/users/:id?', { id: 15});
reverse('/users/:id?', {});
#2
6
I've just created the package reversable-router that solves this along other problems for the routing.
我刚刚创建了包可逆路由器,它解决了路由的其他问题。
Example from the readme:
自述文件中的示例:
app.get('/admin/user/:id', 'admin.user.edit', function(req, res, next){
//...
});
//.. and a helper in the view files:
url('admin.user.edit', {id: 2})
#1
7
Here is your code:
这是你的代码:
function reverse(url, obj) {
return url.replace(/(\/:\w+\??)/g, function (m, c) {
c=c.replace(/[/:?]/g, '');
return obj[c] ? '/' + obj[c] : "";
});
}
reverse('/users/:id/:name', { id: 15, name: 'John' });
reverse('/users/:id?', { id: 15});
reverse('/users/:id?', {});
#2
6
I've just created the package reversable-router that solves this along other problems for the routing.
我刚刚创建了包可逆路由器,它解决了路由的其他问题。
Example from the readme:
自述文件中的示例:
app.get('/admin/user/:id', 'admin.user.edit', function(req, res, next){
//...
});
//.. and a helper in the view files:
url('admin.user.edit', {id: 2})