1. Fetch API 簡介
??fetch
是 ES6 提供的基于 Promise
的 API,用于發送 HTTP 請求并處理服務器響應數據。與傳統的 XMLHttpRequest
相比,fetch
語法更加簡潔,使用 Promise
進行異步處理,避免了回調地獄。
1.1 fetch()
的基本用法
fetch(url, options)
返回一個 Promise
,其中:
-
url
:請求的地址。 -
options
(可選):一個對象,用于設置請求方法、請求頭、請求體等。
示例:
fetch('http://127.0.0.1/get').then(response => response.json()) // 解析 JSON 格式的響應數據.then(data => console.log("get.data:", data)).catch(error => console.log("get.error:", error.message)).finally(() => console.log("get.finally"));
2. 發送不同類型的 HTTP 請求
2.1 發送 GET 請求
GET 請求不需要 body
,通常用于獲取數據。
fetch('http://127.0.0.1/get').then(response => response.json()).then(data => console.log("get.data:", data)).catch(error => console.log("get.error:", error.message)).finally(() => console.log("get.finally"));
2.2 發送 POST 請求(表單數據)
當需要提交數據時,可以使用 POST
方法,并在 headers
指定 Content-Type
。
fetch('http://127.0.0.1/post', {method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded'},body: new URLSearchParams({name: 'theodore',web: 'https://blog.csdn.net/Theodore_1022'})
})
.then(response => response.json())
.then(data => console.log("post.data:", data))
.catch(error => console.log("post.error:", error.message))
.finally(() => console.log("post.finally"));
2.3 發送 POST 請求(JSON 數據)
提交 JSON 數據時,Content-Type
需要設置為 application/json
,并使用 JSON.stringify()
處理 body
。
fetch('http://127.0.0.1/postJson', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({name: 'theodore',web: 'https://blog.csdn.net/Theodore_1022'})
})
.then(response => response.json())
.then(data => console.log("postJson.data:", data))
.catch(error => console.log("postJson.error:", error.message))
.finally(() => console.log("postJson.finally"));
3. 處理 Fetch 響應
fetch
返回的 Promise
解析后得到的是一個 Response
對象,需要進一步解析數據。
fetch('http://127.0.0.1/get').then(response => {if (!response.ok) {throw new Error(`HTTP 錯誤!狀態碼: ${response.status}`);}return response.json();}).then(data => console.log("get.data:", data)).catch(error => console.log("get.error:", error.message));
3.1 解析不同格式的響應數據
fetch
的 Response
對象提供多個方法來解析數據:
-
response.json()
:解析 JSON 格式數據。 -
response.text()
:解析文本數據。 -
response.blob()
:解析二進制數據,如圖片、音視頻。 -
response.arrayBuffer()
:解析為ArrayBuffer
,用于處理二進制流數據。
示例:
fetch('http://127.0.0.1/data').then(response => response.text()).then(text => console.log("text data:", text));
4. 處理超時請求
fetch
默認沒有超時機制,可以使用 AbortController
來手動終止請求。
const controller = new AbortController();
const signal = controller.signal;setTimeout(() => controller.abort(), 5000); // 5 秒后取消請求fetch('http://127.0.0.1/timeout', { signal }).then(response => response.json()).then(data => console.log("data:", data)).catch(error => {if (error.name === 'AbortError') {console.log('請求超時,已取消');} else {console.log('請求失敗:', error.message);}});
5. 處理跨域問題
如果請求跨域,需要服務器配置 CORS(跨域資源共享)。
-
服務器返回
Access-Control-Allow-Origin: *
允許跨域訪問。 -
如果涉及
credentials
(如cookies
),需要設置fetch
的credentials
。
fetch('http://127.0.0.1/protected', {credentials: 'include' // 允許攜帶 cookies
})
.then(response => response.json())
.then(data => console.log("data:", data));
6. 結語
??fetch
是 ES6 現代 Web 開發中常用的 API,它相比傳統 XMLHttpRequest
更加簡潔且基于 Promise
,使得異步代碼更加優雅。掌握 fetch
,可以更輕松地處理 HTTP 請求,提高前端開發效率。