【发布时间】:2021-04-21 10:49:06
【问题描述】:
所以我最近开始学习后端,使用 node/expres。 我正在构建一个用于学习目的的小型 REST API,具有以下路线:
GET /api/products >> to display a list of products
GET /api/cart >> to display list of items inside the cart
DELETE /api/cart/:id >> to delete an item from the cart
现在,我希望能够使用 POST 方法将商品添加到购物车,当然应该是:
/api/cart >> and pass the item id in the body, so req.body.id
或
/api/cart/:id >> and pass the item id with req.prams.id ??
我知道这两种方法都有效,但有人告诉我,使用 POST 方法,最好通过正文传递它,所以我想了解原因,因为在这种特定情况下,我不会创建一个全新的项目(在这种情况下,我当然会通过正文传递数据),但我已经在产品列表中拥有该项目,所以我只想检索它并将其添加到购物车。 是不是如果我为这个 api 创建前端,其中一个会更好地工作?或者整个事情是如何运作的?首选的方法是什么?
谢谢
【问题讨论】:
-
你的模式是正确的。在第二种情况下,即更新记录,我们通常按照惯例使用 PUT 方法。但使用 POST 也可以。
标签: javascript node.js api express