SNahar
SNahar

Reputation: 134

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.

Upvotes: 0

Views: 82

Answers (1)

Abhyudit Jain
Abhyudit Jain

Reputation: 3748

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

Upvotes: 1

Related Questions