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屋!
查看全文