Fetch API速查表:9個(gè)最常見(jiàn)的API請(qǐng)求

來(lái)源 | https://blog.zhangbing.site/2020/11/24/fetch-api-cheatsheet/
對(duì)于Fetch API我相信你已經(jīng)用過(guò)它們很多次了,但是你是否還記得語(yǔ)法?如果能避免在舊項(xiàng)目中尋找半年前使用過(guò)的特定請(qǐng)求的語(yǔ)法,豈不更好?
在本文中,我將列出9個(gè)最常見(jiàn)的Fetch API請(qǐng)求,在你忘記API的時(shí)候可以翻出來(lái)查看。
為什么要使用Fetch API?
如今,我們被所有提供漂亮的SDK的服務(wù)寵壞了,這些SDK將實(shí)際的API請(qǐng)求抽象化,我們只需要使用典型的語(yǔ)言結(jié)構(gòu)來(lái)請(qǐng)求數(shù)據(jù),而不關(guān)心實(shí)際的數(shù)據(jù)交換。
但是,如果你所選擇的平臺(tái)沒(méi)有SDK怎么辦?或者如果你同時(shí)構(gòu)建服務(wù)器和客戶端呢?在這些情況下,你需要自己處理請(qǐng)求,這就是使用Fetch API的方法。
使用Fetch API的簡(jiǎn)單GET請(qǐng)求
fetch('{url}').then(response => console.log(response));
使用Fetch API的簡(jiǎn)單POST請(qǐng)求
fetch('{url}', {method: 'post'}).then(response => console.log(response));
在Fetch API中使用授權(quán)令牌 (Bearer) 進(jìn)行GET
fetch('{url}', {headers: {'Authorization': 'Basic {token}'}}).then(response => console.log(response));
在Fetch API中使用查詢字符串?dāng)?shù)據(jù)進(jìn)行GET
fetch('{url}?var1=value1&var2=value2').then(response => console.log(response));
??在Fetch API中使用CORS進(jìn)行GET
fetch('{url}', {mode: 'cors'}).then(response => console.log(response));
在Fetch API中使用授權(quán)令牌和查詢字符串?dāng)?shù)據(jù)進(jìn)行POST
fetch('{url}?var1=value1&var2=value2', {method: 'post',headers: {'Authorization': 'Bearer {token}'}}).then(response => console.log(response));
在Fetch API中使用表單數(shù)據(jù)進(jìn)行POST
let formData = new FormData();formData.append('field1', 'value1');formData.append('field2', 'value2');fetch('{url}', {method: 'post',body: formData}).then(response => console.log(response));
在Fetch API中使用jsON數(shù)據(jù)進(jìn)行POST
fetch('{url}', {method: 'post',headers: {'Content-Type': 'application/json'},body: JSON.stringify({'field1': 'value1','field2': 'value2'})}).then(response => console.log(response));
在Fetch API中使用JSON數(shù)據(jù)和CORS進(jìn)行POST
fetch('{url}', {method: 'post',mode: 'cors',headers: {'Content-Type': 'application/json'},body: JSON.stringify({'field1': 'value1','field2': 'value2'})}).then(response => console.log(response));
如何處理Fetch API請(qǐng)求的結(jié)果
Fetch API返回一個(gè)Promise。這就是為什么我總是使用 .then() 和回調(diào)函數(shù)來(lái)處理響應(yīng)的原因:
fetch(...).then(response => {// process the response}
但是,如果你處于異步函數(shù)中,也可以等待結(jié)果:
async function getData(){let data = await fetch(...);// process the response}
現(xiàn)在讓我們看一下如何從響應(yīng)中提取數(shù)據(jù):
如何檢查Fetch API響應(yīng)的狀態(tài)碼
發(fā)送POST,PATCH和PUT請(qǐng)求時(shí),我們通常對(duì)返回狀態(tài)代碼感興趣:
fetch(...).then(response => {if (response.status == 200){// all OK} else {console.log(response.statusText);}});
如何獲取Fetch API響應(yīng)的簡(jiǎn)單值
某些API端點(diǎn)可能會(huì)發(fā)回使用你的數(shù)據(jù)創(chuàng)建的新數(shù)據(jù)庫(kù)記錄的標(biāo)識(shí)符:
var userId;fetch(...).then(response => response.text()).then(id => {userId = id;console.log(userId)});
如何轉(zhuǎn)換Fetch API響應(yīng)的JSON數(shù)據(jù)
但是在大多數(shù)情況下,你會(huì)在響應(yīng)正文中接收J(rèn)SON數(shù)據(jù):
var dataObj;fetch(...).then(response => response.json()).then(data => {dataObj = data;console.log(dataObj)});
請(qǐng)記住,只有在兩個(gè)Promises都解決后,你才能訪問(wèn)數(shù)據(jù)。這有時(shí)會(huì)讓人有點(diǎn)困惑,所以我總是喜歡使用async方法并等待結(jié)果。
async function getData(){var dataObj;const response = await fetch(...);const data = await response.json();dataObj = data;console.log(dataObj);}
總結(jié)
這些示例應(yīng)該涵蓋了大多數(shù)情況。
我是否錯(cuò)過(guò)了什么,一個(gè)你每天都在使用的請(qǐng)求?或者是其他你正在苦惱的事情?請(qǐng)?jiān)谠u(píng)論區(qū)上告訴我。
最后,你也可以以可打印的形式獲得這份備忘單:https://ondrabus.com/
本文完~

