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);
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.
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.
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; });
In Express. js, you can directly use the req. query() method to access the string variables.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With