Wildan S. Nahar Wildan S. Nahar - 1 month ago 4
Node.js Question

Express get api with params

I'm new to express API. I have an API with http GET and I'd like to get data from mongodb that matches to certain criteria. Here is my mongodb documents looks like :

{value:"24", category:"low"} {value:"30", category:"middle"}, {value:"23", category:"low"}


And my code in the server side looks like this :

`router.route('/temps')
.get(function(req,res){
Temp.find(function(err, temps){
if(err){
res.send(err)
} else {
var category = req.params.category
console.log(temps)
res.format({
json: function(){
res.json(temps)
},
html: function(){
res.render('temps', {
title: 'All temps',
temps: temps
});
},
});
}
})
})`


I wanna get all values where the category is
low
with query like this :
/temps?category=low
. How can I modify the codes above? Thanks for the help.

Answer

If you check for req.params.category then your route should be /temp/:category for example, /temp/low because req.params is for path parameters.

If you want to check for query parameters like /temp?category=low then you should check for req.query.category