4

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?

5
  • None of them are required - //, /1/, and /1/2 should all work Commented Feb 9, 2015 at 15:00
  • If one is empty the request becomes /2, not //2, and what you have done will serve /2 if one is empty. Commented Feb 9, 2015 at 15:00
  • so in this case use regex Commented Feb 9, 2015 at 15:01
  • @NaeemShaikh, can you please give an example of a regexp that would keep named parameters? Commented Feb 9, 2015 at 15:04
  • nope.. i m not that good with regex Commented Feb 9, 2015 at 15:08

2 Answers 2

3
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:'' }
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to do this keeping parameter names?
You mean req.params.one/two? I'm afraid not. When you use regex you can't use named parameters.
Sorry, but the //b => {0:'' , 1:'b'} return instead a 404
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.