Fetch與Axios:區別、聯系、優缺點及使用差異
文章目錄
- Fetch與Axios:區別、聯系、優缺點及使用差異
- 一、聯系
- 二、區別
- 1. 瀏覽器支持與兼容性
- 2. 響應處理
- 3. 請求攔截和響應攔截
- 4. 錯誤處理
- 三、優缺點
- 1. Fetch API
- 優點
- 缺點
- 2. Axios
- 優點
- 缺點
- 四、使用上的差異和特性
- 1. 發送POST請求
- 2. 取消請求
- 總結
在現代Web開發中,數據交互是必不可少的環節。Fetch API和Axios是兩種常用的HTTP客戶端工具,用于在瀏覽器和Node.js環境中發起HTTP請求。下面我們來詳細探討它們的區別、聯系、優缺點以及使用上的差異。
一、聯系
Fetch API和Axios的主要目的都是發起HTTP請求,實現客戶端與服務器之間的數據交互。它們都支持常見的HTTP方法,如GET、POST、PUT、DELETE等,并且可以處理各種類型的響應數據,如JSON、文本、二進制數據等。
二、區別
1. 瀏覽器支持與兼容性
- Fetch API:是現代瀏覽器原生支持的API,無需額外引入庫。但在舊版本的瀏覽器(如IE)中不支持,需要使用polyfill來實現兼容性。
- Axios:是一個第三方庫,需要引入才能使用。它支持所有主流瀏覽器,包括舊版本的IE,并且在Node.js環境中也能使用。
2. 響應處理
- Fetch API:返回的是一個Promise對象,需要手動解析響應數據。例如,要獲取JSON格式的響應數據,需要調用
response.json()
方法。
fetch('https://api.example.com/data').then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error));
- Axios:會自動解析響應數據,默認情況下返回的就是解析后的JSON對象。
axios.get('https://api.example.com/data').then(response => console.log(response.data)).catch(error => console.error(error));
3. 請求攔截和響應攔截
- Fetch API:本身不支持請求攔截和響應攔截,需要手動實現。
- Axios:內置了請求攔截和響應攔截功能,可以在請求發送前和響應返回后進行一些處理,如添加請求頭、錯誤處理等。
// 請求攔截
axios.interceptors.request.use(config => {// 在發送請求之前做些什么config.headers.Authorization = 'Bearer ' + token;return config;
}, error => {// 對請求錯誤做些什么return Promise.reject(error);
});// 響應攔截
axios.interceptors.response.use(response => {// 對響應數據做點什么return response;
}, error => {// 對響應錯誤做點什么return Promise.reject(error);
});
4. 錯誤處理
- Fetch API:只有在網絡請求失敗時才會reject Promise,即使服務器返回404、500等狀態碼,Promise仍然會resolve。需要手動檢查
response.ok
屬性來判斷請求是否成功。
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));
- Axios:在請求失敗時會reject Promise,并且會包含詳細的錯誤信息,如狀態碼、錯誤消息等。
axios.get('https://api.example.com/data').then(response => console.log(response.data)).catch(error => {if (error.response) {// 請求已發出,但服務器響應狀態碼不在 2xx 范圍內console.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {// 請求已發出,但沒有收到響應console.log(error.request);} else {// 其他錯誤console.log('Error', error.message);}});
三、優缺點
1. Fetch API
優點
- 原生支持,無需引入額外庫,減少項目體積。
- 語法簡潔,符合現代JavaScript的Promise風格。
缺點
- 瀏覽器兼容性差,需要polyfill。
- 響應處理繁瑣,需要手動解析。
- 錯誤處理不夠直觀。
2. Axios
優點
- 支持所有主流瀏覽器和Node.js環境。
- 內置請求攔截和響應攔截功能,方便處理請求和響應。
- 自動解析響應數據,錯誤處理更完善。
- 支持取消請求、自動轉換JSON數據等功能。
缺點
- 需要引入第三方庫,增加項目體積。
四、使用上的差異和特性
1. 發送POST請求
- Fetch API:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ key: 'value' })
}).then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error));
- Axios:
axios.post('https://api.example.com/data', { key: 'value' }).then(response => console.log(response.data)).catch(error => console.error(error));
2. 取消請求
- Fetch API:使用
AbortController
實現超時取消請求。
const controller = new AbortController();
const signal = controller.signal;// 設置超時時間為3000毫秒
const timeoutId = setTimeout(() => {controller.abort();
}, 3000);fetch('https://api.example.com/data', { signal }).then(response => {clearTimeout(timeoutId);return response.json();}).then(data => console.log(data)).catch(error => {if (error.name === 'AbortError') {console.log('請求超時被取消');} else {console.error(error);}});
- Axios:使用
CancelToken
實現超時取消請求。
const CancelToken = axios.CancelToken;
const source = CancelToken.source();// 設置超時時間為3000毫秒
const timeoutId = setTimeout(() => {source.cancel('請求超時被取消');
}, 3000);axios.get('https://api.example.com/data', {cancelToken: source.token
}).then(response => {clearTimeout(timeoutId);console.log(response.data);}).catch(error => {if (axios.isCancel(error)) {console.log(error.message);} else {console.error(error);}});
總結
Fetch API和Axios各有優缺點,選擇使用哪一個取決于項目的具體需求。如果項目對瀏覽器兼容性要求不高,且希望減少依賴,可以選擇Fetch API;如果需要處理復雜的請求和響應,或者需要支持舊版本的瀏覽器,Axios是更好的選擇。