How to make parameters Optional in node JS rest API

user1398291 picture user1398291 · Jun 10, 2014 · Viewed 8.4k times · Source

We need to Expose REST endpoint. There are three parameters, how to make those optional. Requirement is it should work with any one of those parameters.

e.g. http://server:port/v1/api/test-api/userId/UnameName/userEmail

app.get('v1/api/test-api/:userId/:userName/:userEmail', function(req, res){

});

When we call by passing all three parameters it works fine. But we want to make it work by passing only userId or any of these three parameters. When we pass less parameters its giving error Cannot GET /v1/api/test-api/test5/123

How to make parameters optional while exposing endpoint?

Answer

thebiglebowski11 picture thebiglebowski11 · Jun 10, 2014

you need to structure the route like this:

app.get('path/:required/:optional?*, ...)