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