部分拆分的快速外卡路线
Express wild card route with parts split
我在 SO 上用谷歌搜索并检查了其他答案,但它们不是我要找的。
我的外卡路线:
app.all("/admin/*", function(request, response){
});
request.params
提供
如果 uri 是 /admin/login
= { '0': 'login' }
如果 uri 是 /admin/dashboard
= { '0': 'dashboard' }
如果 uri 是 /admin/dashboard/events
= { '0': 'dashboard/events' }
但我的期望是。
{ '0': 'dashboard', '1': 'events' } //made up, not an actual result
也许我的处理方式不对,请大家多多指教。
您可以简单地添加更多路线模式:
app.all("/admin/*/*", function(req, res) {
// Going to /admin/foo/bar gives you
// { '0': 'foo', '1': 'bar' }
console.log(req.params);
res.end();
});
一个更好的主意可能是命名您的路线部分,如下所示:
app.all("/admin/:one/:two", function(req, res) {
// Going to /admin/foo/bar gives you
// { one: 'foo', two: 'bar' }
console.log(req.params);
res.end();
});
在正则表达式中使用捕获组。这将反映在 request.params
中。然后拆分匹配的字符串以生成结果数组。要学习正则表达式,您可以前往 http://regexr.com/.
app.all(/^\/admin\/(.*)/, function(req, resp) {
var params = req.params[0] && req.params[0].split('/');
});
编辑:没有参数时不会抛出错误。
我在 SO 上用谷歌搜索并检查了其他答案,但它们不是我要找的。
我的外卡路线:
app.all("/admin/*", function(request, response){
});
request.params
提供
如果 uri 是 /admin/login
= { '0': 'login' }
如果 uri 是 /admin/dashboard
= { '0': 'dashboard' }
如果 uri 是 /admin/dashboard/events
= { '0': 'dashboard/events' }
但我的期望是。
{ '0': 'dashboard', '1': 'events' } //made up, not an actual result
也许我的处理方式不对,请大家多多指教。
您可以简单地添加更多路线模式:
app.all("/admin/*/*", function(req, res) {
// Going to /admin/foo/bar gives you
// { '0': 'foo', '1': 'bar' }
console.log(req.params);
res.end();
});
一个更好的主意可能是命名您的路线部分,如下所示:
app.all("/admin/:one/:two", function(req, res) {
// Going to /admin/foo/bar gives you
// { one: 'foo', two: 'bar' }
console.log(req.params);
res.end();
});
在正则表达式中使用捕获组。这将反映在 request.params
中。然后拆分匹配的字符串以生成结果数组。要学习正则表达式,您可以前往 http://regexr.com/.
app.all(/^\/admin\/(.*)/, function(req, resp) {
var params = req.params[0] && req.params[0].split('/');
});
编辑:没有参数时不会抛出错误。