fetch 的注意事項

懶人包。

簡述

Content-type

你傳什麼資料就應該寫什麼格式:

  • Json => application/json
  • Form => application/x-www-form-urlencoded
  • FormData => 雖然是 multipart/form-data 但不需要寫

Credential

簡單來說就是「發 request 時要不要帶上 Cookie」,預設是「不會」,如果想要的話得加上這段設定:

1
2
3
4
5
6
7
8
fetch(url, {
// cros
credentials: 'include'
// 同源才帶
credentials: 'same-origin',
// 保證不帶
credentials: 'omit'
})

Mode

最常被人誤解的東西,所以特別強調一下:

  • 這不是用來破除 CROS 的限制
  • 這不是用來破除 CROS 的限制
  • 這不是用來破除 CROS 的限制

他的目的是告訴瀏覽器:

對,我知道 server 沒有開 CROS,但我本來就沒有想拿到 response,所以你不要讓程式跑到 catch 那邊。

所以說如果這樣設定:

1
2
3
4
5
6
7
8
9
10
fetch(lidemy, {
method: 'POST',
body: 'name=peanu&age=20&gender=man',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
mode: "no-cors"
})
.then(res => console.log(res))
.catch(err => console.log(err))

就會成功拿到 response,不過是「透明的」:

1
2
3
4
5
6
7
8
Response {
type: 'opaque',
url: '',
redirected: false,
status: 0,
ok: false,
// ...
}
用 Promise 來包裝 XMLHttpRequest fetch 發 post 的方式
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×