基本語法
fetch函數用于發起網絡請求,返回一個Promise對象。基本語法如下:
fetch(url, options).then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error));
GET請求
發起一個簡單的GET請求,獲取JSON數據:
fetch('https://api.example.com/data').then(response => {if (!response.ok) {throw new Error('Network response was not ok');}return response.json();}).then(data => console.log(data)).catch(error => console.error('Error:', error));
POST請求
發送JSON數據到服務器:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({key1: 'value1',key2: 'value2'})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
處理響應
fetch返回的Response對象包含多種方法處理不同格式的響應:
fetch('https://api.example.com/data').then(response => {if (response.ok) {return response.text(); // 或.json(), .blob(), .arrayBuffer()等}throw new Error('Network response was not ok');}).then(data => console.log(data)).catch(error => console.error('Error:', error));
錯誤處理
由于fetch只在網絡錯誤時reject,需要手動處理HTTP錯誤狀態:
fetch('https://api.example.com/data').then(response => {if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return response.json();}).then(data => console.log(data)).catch(error => console.error('Error:', error));
請求配置
可配置的選項包括method、headers、body、mode、credentials等:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer token'},body: JSON.stringify({key: 'value'}),credentials: 'include' // 包含cookies
});
取消請求
使用AbortController可以取消fetch請求:
const controller = new AbortController();
const signal = controller.signal;fetch('https://api.example.com/data', {signal}).then(response => response.json()).then(data => console.log(data)).catch(error => {if (error.name === 'AbortError') {console.log('Fetch aborted');} else {console.error('Error:', error);}});// 取消請求
controller.abort();