iT邦幫忙

2021 iThome 鐵人賽

DAY 17
1
自我挑戰組

登堂入室!前端工程師的觀念技術 _30_ 題系列 第 17

16. HTTP request methods ( 下 )--- PUT vs. PATCH

延續昨天的文章15. HTTP request methods ( 上 )--- GET vs. POST,今天來複習PUT和PATCH。

PUT


The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times.

PUT請求方法用於創建更新資料

雖然POST也能夠創建資料,差別在PUT有冪等(Idempotent)的性質。

冪等的作用是為了確保在請求失敗時,可以重新進行請求,而不會造成多餘的影響。PUT更新資料的方式是覆蓋整筆資料,所以是一個Idempotent method。

範例

昨天嘗試取得過的第一筆資料,原本是長這樣子的:

// output
{
	"userId": 1,
	"id": 1,
	"title": "delectus aut autem",
	"completed": false
}

來修改一下內容:

fetch('https://jsonplaceholder.typicode.com/todos/1',   {  //目標URL
  method: 'PUT',  // 使用PUT
  body: JSON.stringify({
    title: 'Winnie the Pooh',  // 改個標題
    id: 1,
    userId: 1,
    completed: true,
    notes: "new Item"  // 增加了一個條目
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then(response => response.json())
  .then(json => { console.log(json) ;})

成功PUT結果:

{
    "title": 'Winnie the Pooh', 
    "id": 1,
    "userId": 1,
    "completed": true,
    "notes": "new Item" 
  }

可以用response.status來確認請求的狀態,在.json()加入這一行:

  .then(response => sonsole.log(response.status))  

PUT的性質

  • safe(安全) : 會更動資料的內容,因此是不安全的。(X)
  • idempotent(冪等) : 即使請求多次,server都會回傳相同的結果,所以也是冪等的。(O)
  • cacheable(可緩存的) : 不會被緩存。(X)

PATCH


PATCH用於局部資料的更新。

A PATCH request is considered a set of instructions on how to modify a resource. Contrast this with PUT; which is a complete representation of a resource.

相較於PUT是覆蓋整筆資料,PATCH只會更動部分的資料。

一樣看到例子,我們還是借用第一筆資料:

// output
{
	"userId": 1,
	"id": 1,
	"title": "delectus aut autem",
	"completed": false
}

PATCH請求:

fetch('https://jsonplaceholder.typicode.com/todos/1',   {  
  method: 'PATCH',
  body: JSON.stringify({
    completed: true,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then(response => response.json())
  .then(json => { console.log(json) ;})

成功PATCH的結果:

// output
{
	"userId": 1,
	"id": 1,
	"title": "delectus aut autem",
	"completed": true
}

所以如果不小心寫成PUT,資料會出大事:

{
	"id": 1,
    "completed": true,
  }

整筆資料會被覆蓋過去,這就是PUT和PATCH的差異。

PATCH的性質

  • safe(安全) : 會更動資料的內容,因此是不安全的。(X)
  • idempotent(冪等) : 請求多次就會執行多次要求,所以不是冪等的。(X)
  • cacheable(可緩存的) : 如果headers裡的Content-Location有指定,是可以被暫時儲存。但一般不會這麼做,而且這在Firefox不支援。(△,和POST一樣)

PUT vs. PATCH


延續昨天的表格:
\ | GET | POST | PUT | PATCH
--|-----|-----
用途 | 獲得資料 | 新增資料 | 新增/修改資料(整筆覆蓋) | 修改資料
安全性 | O(唯讀) | X | X | X
冪等 | O | X | O | X
可緩存的| O | △ | X |△

參考資料:


CTRL+S不能存文章真的不太方便,還好這篇不長,不然剛剛關錯分頁一半沒存到,背真的涼了一下QQ


上一篇
15. HTTP request methods ( 上 )--- GET vs. POST
下一篇
17. 解釋 Same-Origin Policy
系列文
登堂入室!前端工程師的觀念技術 _30_ 題31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言