使用URL中定义的查询参数通过带有节点/表达式的RESTful API过滤资源?

时间:2018-11-01 17:22:27

标签: node.js express

如何在node / express上做这种事情

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

但是按状态过滤? 举例来说,我想使用这种类型的路线/users/123/posts?state=published, 我该如何在节点上拥抱它?

1 个答案:

答案 0 :(得分:0)

明确地说,不需要在路由中指定URL查询字符串。而是使用req.query访问它们:

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

这将处理以下网址:/users/123/posts?state=published