Express.js 路由:可选的 splat 参数? [英] Express.js routing: optional splat param?
本文介绍了Express.js 路由:可选的 splat 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一条看起来像这样的路线:
I have a route that looks like this:
app.all('/path/:namedParam/*splat?',function(req,res,next){
if(!req.params.length){
// do something when there is no splat
} else {
// do something with splat
}
});
但是,这不起作用 - 如果我调用 path/foo/bar
它会命中路由,但是如果我调用 path/foo
,它不会.
however, this doesn't work - if I call path/foo/bar
it hits the route, but if I call path/foo
, it doesn't.
是否可以有一个可选的 splat 参数,或者我是否必须使用正则表达式来检测这个?
Is it possible to have an optional splat param, or do I have to use a regex to detect this?
编辑:
更清楚地说,以下是我想要达到的要求:
to be clearer, here are the requirements I'm trying to achieve:
- 第一个和第二个参数是必需的
- 第一个参数是静态的,第二个是命名参数.
- 可以附加任意数量的可选附加参数,并且仍然可以命中路由.
- the first and second params are required
- the first param is static, the second is a named param.
- any number of optional additional params can be appended and still hit the route.
推荐答案
这适用于 express 4 上的/path 和/path/foo,注意 ?
之前的 *
.
This works for /path and /path/foo on express 4, note the *
before ?
.
router.get('/path/:id*?', function(req, res, next) {
res.render('page', { title: req.params.id });
});
这篇关于Express.js 路由:可选的 splat 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文