3

I'm looking to add an optional parameter to an express route where var1 has to be set but var 2 can be ommited (/test/0 and /test/0/0 should both work).

I could create another rule, or juste evaluate the string "test/0/0" but I'm wondering if there is no other way.

app.get('/test/:var1/:var2', function(req, res){
    // DO SOMETHING
});

Thanks !

1 Answer 1

7
app.get('/test/:var1/:var2*?',function(req,res)
   {
if(!req.params.var2){
// do something when there is no optionalParam
  }
res.json({ var: req.params.var1,
          var2: req.params.var2 });

});

just call

http://127.0.0.1:8080/test/44

output

{"var":"44"}

incase of passing both

{"var":"44","var2":"77"}

Sign up to request clarification or add additional context in comments.

1 Comment

What does * do ?

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.