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?
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:'' }
req.params.one/two? I'm afraid not. When you use regex you can't use named parameters.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.
//,/1/, and/1/2should all workoneis empty the request becomes/2, not//2, and what you have done will serve/2ifoneis empty.