Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过req.params.id Vs req.body.id传递id_Javascript_Node.js_Api_Express - Fatal编程技术网

Javascript 通过req.params.id Vs req.body.id传递id

Javascript 通过req.params.id Vs req.body.id传递id,javascript,node.js,api,express,Javascript,Node.js,Api,Express,所以我最近开始学习后端,使用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 现在,我希望能

所以我最近开始学习后端,使用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 

我知道这两种方法都有效,但有人告诉我,使用POST方法时,最好通过正文传递,因此我想了解为什么,因为在这种特定情况下,我没有创建一个全新的项目(在这种情况下,我当然会通过正文传递数据),但我已经在产品列表中有了该项目,所以我只想检索它并将其添加到购物车中。 如果我为这个api创建前端,其中一个会更好吗?或者整个事情是如何运作的?首选的方法是什么


谢谢

您可以在正文中容纳比url中更多(多样化)的数据。您可以在正文中传递任何字符串(特殊字符),而在url中编码这些字符串将使您容易受到状态414(请求URI过长)的攻击。在传递数组和复杂对象时,使用主体要容易得多:)

您的模式是正确的。在第二种情况下,即更新记录,我们通常按照约定使用PUT方法。但对于POST,它也会起作用。
/api/cart/:id >> and pass the item id with req.prams.id ??