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 !

fbhcf
  • 111
  • 1
  • 8

1 Answers1

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"}

Community
  • 1
  • 1
Adiii
  • 54,482
  • 7
  • 145
  • 148