Express.js路由:可选的空白参数? [英] Express.js routing: optional spat param?
本文介绍了Express.js路由:可选的空白参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
app.all('/ path /:namedParam / * splat? ',function(req,res,next){
if(!req.params.length){
//当没有splat时执行某些操作
} else {
/ /做某事与splat
}
});
但是,这不行 - 如果我调用 path / foo / bar
它点击路线,但如果我调用 path / foo
,则不会。
可以使用可选的拼写参数,还是使用正则表达式来检测?
修改:
要更清楚,以下是我要实现的要求:
- 第一个和第二个参数是必需
- 第一个参数是静态的,第二个参数是一个命名参数。
-
解决方案
这个作品适用于express 4上的/ path和/ path / foo,请注意之前的
。 *
?
router.get('/ path /:id *?',function(req,res,next){
res.render('page',{title:req.params.id});
});
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
}
});
however, this doesn't work - if I call path/foo/bar
it hits the route, but if I call path/foo
, it doesn't.
Is it possible to have an optional splat param, or do I have to use a regex to detect this?
Edit:
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.
解决方案
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路由:可选的空白参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文