Ad

How To Make A Single Express Endpoint For Multiple Optional Parameters For Database Query?

- 1 answer

I am stuck at routing in Express. I want to make a single route for multiple optional request parameters to fetch records from the database based on the given parameter by the client.

I am using this:

"/search/:firstName?/:lastName?/:department?/:designation?"

Problem in the above url is : if user wants to search by only department then department will be mapped with firstName

Ad

Answer

A better way to go about it is using query parameters. So if the user only wants to search by department, an example request url will look like this:

/search?department=education

Multiple parameters will be separated by a &. For e.g:

/search?department=education&firstName=john

You can access this information in express like this:

// ...
router.get('search', function(req, response){
      var department = req.query.department;
      var firstName = req.query.firstName;
      // ...
})
Ad
source: stackoverflow.com
Ad