Fetch API速查表:9個最常見的API請求
對于Fetch API我相信你已經(jīng)用過它們很多次了,但是你是否還記得語法?如果能避免在舊項目中尋找半年前使用過的特定請求的語法,豈不更好?
在本文中,我將列出9個最常見的Fetch API請求,在你忘記API的時候可以翻出來查看。
為什么要使用Fetch API?
如今,我們被所有提供漂亮的SDK的服務(wù)寵壞了,這些SDK將實際的API請求抽象化,我們只需要使用典型的語言結(jié)構(gòu)來請求數(shù)據(jù),而不關(guān)心實際的數(shù)據(jù)交換。
但是,如果你所選擇的平臺沒有SDK怎么辦?或者如果你同時構(gòu)建服務(wù)器和客戶端呢?在這些情況下,你需要自己處理請求,這就是使用Fetch API的方法。
發(fā)送簡單GET請求
- fetch('{url}').then(response => console.log(response));
發(fā)送簡單POST請求
- fetch('{url}', {
- method: 'post'
- }).then(response => console.log(response));
使用授權(quán)令牌進(jìn)行GET
- fetch('{url}', {
- headers: {
- 'Authorization': 'Basic {token}'
- }
- }).then(response => console.log(response));
使用查詢字符串?dāng)?shù)據(jù)進(jìn)行GET
- fetch('{url}?var1=value1&var2=value2')
- .then(response => console.log(response));
使用CORS進(jìn)行GET
- fetch('{url}', {
- mode: 'cors'
- }).then(response => console.log(response));
使用授權(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));
使用表單數(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));
使用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));
使用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請求的結(jié)果
Fetch API返回一個Promise。這就是為什么我總是使用 .then() 和回調(diào)函數(shù)來處理響應(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請求時,我們通常對返回狀態(tài)代碼感興趣:
- fetch(...).then(response => {
- if (response.status == 200){
- // all OK
- } else {
- console.log(response.statusText);
- }
- });
如何獲取Fetch API響應(yīng)的簡單值
某些API端點可能會發(fā)回使用您的數(shù)據(jù)創(chuàng)建的新數(shù)據(jù)庫記錄的標(biāo)識符:
- var userId;
- fetch(...)
- .then(response => response.text())
- .then(id => {
- userId = id;
- console.log(userId)
- });
如何轉(zhuǎn)換Fetch API響應(yīng)的JSON數(shù)據(jù)
但是在大多數(shù)情況下,您會在響應(yīng)正文中接收J(rèn)SON數(shù)據(jù):
- var dataObj;
- fetch(...)
- .then(response => response.json())
- .then(data => {
- dataObj = data;
- console.log(dataObj)
- });
請記住,只有在兩個Promises都解決后,你才能訪問數(shù)據(jù)。這有時會讓人有點困惑,所以我總是喜歡使用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ù)情況。
我是否錯過了什么,一個你每天都在使用的請求?或者是其他你正在苦惱的事情?請在評論區(qū)上告訴我。
最后,你也可以以可打印的形式獲得這份備忘單:https://ondrabus.com/fetch-api-cheatsheet
原文:https://www.freecodecamp.org/news/fetch-api-cheatsheet/
作者:Ondrej Polesny
本文轉(zhuǎn)載自微信公眾號「 前端全棧開發(fā)者」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系 前端全棧開發(fā)者公眾號。