fetch 發 post 的方式

懶人包。

簡述

只是介紹一下該怎麼寫參數:

  1. 傳送 JSON 格式
1
2
3
4
5
6
7
8
9
10
11
12
fetch(url, {
// HTTP method
method: 'POST',
// 資料
body: JSON.stringify(json),
headers: {
// 資料傳什麼這邊就寫什麼
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
  1. 傳送 Form 表單(formData)

這個就跟 XHR 一樣,不要再設定 Content-type 了,不然格式會跑掉。

1
2
3
4
5
6
7
8
9
10
11
const formData = new FormData();
formData.append('name', 'PeaNu');
formData.append('age', '22');
formData.append('gender', 'man');

fetch(url, {
method: 'POST',
body: formData,
})
.then(res => console.log(res))
.catch(err => console.log(err))
  1. 傳送 Form 表單(一般的表單)
1
2
3
4
5
6
7
8
9
10
fetch(api200, {
method: 'POST',
body: 'name=peanu&age=20&gender=man',
headers: {
// 記得加這行
'Content-type': 'application/x-www-form-urlencoded'
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
fetch 的注意事項 fetch 處理錯誤的方式
Your browser is out-of-date!

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

×