Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express routing GET with search params

I have two GET routes for get stores but, one route is for get all stores and the other route is for get just nearby stores.

1) The url request for get all stores is as follows:

http://mydomain/stores

2) The url for get all nearby stores:

http://mydomain/stores?lat={lat}&lng={lng}&radius={radius}

The question is:

How can I map those urls properly in Express, in a way to redirect each route to the corresponding method?

app.get('/stores', store.getAll);

app.get('/stores', store.getNear);
like image 731
vitorvigano Avatar asked Jan 29 '14 17:01

vitorvigano


People also ask

How can you capture query params sent by GET method?

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

Can get requests have query parameters?

For GET requests, input can be specified only as query parameters, because a GET request cannot have a body. This example shows a GET request on the search resource, with two query parameters in the query string.

How do you access GET parameters after Express?

We can access these route parameters on our req. params object using the syntax shown below. app. get(/:id, (req, res) => { const id = req.params.id; });

How do you get variables in Express JS in the GET method?

In Express. js, you can directly use the req. query() method to access the string variables.


1 Answers

app.get('/stores', function(req, res, next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    store.getNear(req, res, next);
  } else {
    store.getAll(req, res, next)
  };
});

edit - a second way to do it:

store.getNear = function(req, res, next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    // do whatever it is you usually do in getNear
  } else {  // proceed to the next matching routing function
    next()
  };
}
store.getAll = function(req, res, next){
  // do whatever you usually do in getAll
}

app.get('/stores', store.getNear, store.getAll)
// equivalent:
// app.get('/stores', store.getNear)
// app.get('/stores', store.getAll)
like image 159
Plato Avatar answered Nov 15 '22 06:11

Plato