【问题标题】:How to prevent endpoint clashing while developing REST API in Express application在 Express 应用程序中开发 REST API 时如何防止端点冲突
【发布时间】:2020-04-03 18:48:09
【问题描述】:

我有以下rest api来获取快递申请中的订单

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", ...) 

当我使用邮递员进行查询时,顶部的查询正在执行,但底部的查询不执行?关于如何通过 REST API 构建的任何建议。谢谢。

【问题讨论】:

    标签: javascript node.js rest express


    【解决方案1】:

    您不会将查询字符串放入 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 设计中)将它作为具有一条路由的查询字符串中的第一个选项更有意义。

    【讨论】:

    • 谢谢你,实际上,过了一会儿,这正是我所做的。不过感谢您的回答!
    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 2019-05-07
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多