如何为RESTful API实现查询string参数

我是新来的RESTful API,我已经成功地实现了我的API的GET和DELETE命令(GET本地主机:4000 / api,邮递员上的DELETE localhost:4000 / api工作正常)。

我的get代码如下所示:

router.get('/', function(req, res) { user.find({}, function(err, users) { if(err){ res.status(404).send({ message: err, data: [] }); } else { res.status(200).send({ message: 'OK', data: users }); } }); }); 

现在我想实现使用参数。 例如,我想实现类似sorting的地方

http:// localhost / 4000 / api / users?sort = {“name”:1}(1-升序; -1 – 降序)

将意味着按升序sorting名称。

我不知道该怎么做是:

  1. 我该如何使这种“sorting”工作?

  2. 如何select要sorting的字段?

请帮忙!

你只能通过命令(asc,desc),如果你想按名称sorting,你可以这样做http:// localhost / 4000 / api / users?order = -1或http:// localhost / 4000 / api /用户?&顺序= 1

然后在你的控制器

 router.get('/', function(req, res) { let order = req.qeury.order; user .find({}) .sort({"name": order}) .exec(function(err, users) { if(err){ res.status(404).send({ message: err, data: [] }); } else { res.status(200).send({ message: 'OK', data: users }); } }); 

});

如果你使用mongoose.js来做这些工作

我经常使用的一个很酷的解决scheme是以下forms

/api/users?sort=-name|+firstname

我使用| 用于多个字段sorting,以及-对于desc+ for asc

在快递中:

 const { sort } = req.query; // sort = '-name|+firstname'; const order = sort.split('|') // will return an array ['-name', '+firstname'] .reduce((order, item) => { const direction = item.charAt(0) === '-' ? -1 : 1; const field = item.substr(1); order[field] = direction; return order; }, {}) // order {'name': -1, 'firstname': 1} users.find({}).sort(order); // do your logic