我有以下剩余 API 来获取 express 应用程序中的订单
http://localhost:2000/api/orders/chemists?orderBy=date&startDate=date1&endDate=date2
http://localhost:2000/api/orders/chemists?orderBy=chemist&startDate=date1&endDate=date2
我的查询如下...
router.get("/chemists?orderBy=date", ...)
router.get("/chemists?orderBy=chemist", ...)
当我使用 postman 进行查询时,顶部的查询正在执行,但底部的查询没有执行?有关如何通过 REST API 构建的任何建议。谢谢。
最佳答案
您不会将查询字符串放入 Express 的路由定义中。如果您打算保留该 URL 结构,则需要一个路由处理程序并根据 req.query
中的值使用 if
:
router.get("/chemists", (req, res) => {
if (req.query.orderBy === "date") {
// handle /chemists?orderBy=date
} else if (req.query.orderBy === "chemist") {
// /chemists?orderBy=chemist
} else {
// handle neither chemist or date specified
}
});
如果您真的非常想要在 Express 中为它们提供单独的路由,则必须将 URL 设计更改为如下所示:
/chemists/date
/chemists/person
然后您可以为每个声明一条单独的路线。由于这种排序顺序实际上只是请求的一个属性(无论哪种方式都请求相同的资源),因此将其作为具有一条路由的查询字符串中的第一个选项更有意义(在 REST 设计中)。
关于javascript - 在 Express 应用程序中开发 REST API 时如何防止端点冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018566/