daniel gon
daniel gon

Reputation: 159

Use query parameters defined in URL for filtering a resource from a RESTful API with node/express?

How can I do this type of thing on node/express

app.get("/users/:id/state/:state", (req, res) => {
      if (req.params.state== 'Published') {
            //do somehting
      } else {
            //do something
      }
});

but filtering by state? Exampe, I wanna have this type of route /users/123/posts?state=published, how do I have to hendle it on node?

Upvotes: 2

Views: 1971

Answers (1)

mihai
mihai

Reputation: 38573

In express, URL query strings do not need to be specified in the route. Instead, you access them using req.query:

app.get("/users/:id/posts", (req, res) => {
    if (req.query.state  == 'published') {
      console.log("published");
    } else {
      console.log("not published");
    }
});

This will process the url: /users/123/posts?state=published

Upvotes: 1

Related Questions