Reputation: 28402
How do I specify a route with a parameter that can be empty?
e.g. /:one?/:two?
handles /1/2
, but does not handle //2
, how do I a make a route to catch both the uris?
Upvotes: 4
Views: 4198
Reputation: 21
Long time since the question was asked, but I had the same problem and found a different solution using named parameters:
app.get('/:one(.{0,})/:two(.{0,})', (req, res) => {
const one = req.params.one;
const two = req.params.two;
});
Inside the paranthesis there is a regex specification of the named parameter. Note the comment in the Express documentation:
In Express 4.x, the * character in regular expressions is not interpreted in the usual way. As a workaround, use {0,} instead of *. This will likely be fixed in Express 5.
Upvotes: 2
Reputation: 34687
app.get(/\/(.*)\/(.*)/, function(req, res) {
var one = req.params[0];
var two = req.params[1];
});
/a/b => {0:'a', 1:'b'}
/a/ => {0:'a', 1:'' }
//b => {0:'' , 1:'b'}
// => {0:'' , 1:'' }
Upvotes: 3