Express JS reverse URL route (Django style)

爱⌒轻易说出口 提交于 2019-11-30 05:27:58

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?', {});

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})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!