Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make parameters Optional in node JS rest API

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?

like image 919
user1398291 Avatar asked Dec 02 '22 16:12

user1398291


1 Answers

you need to structure the route like this:

app.get('path/:required/:optional?*, ...)
like image 156
thebiglebowski11 Avatar answered Jan 31 '23 11:01

thebiglebowski11