在 JavaScript 中,Axios 和原生的 Fetch API 都用於發出 HTTP 請求,但它們在特性、易用性和功能方面存在一些差異。細分如下:
axios:
Axios 簡化了發出請求和處理回應。它會自動解析 JSON 回應,使其更易於使用。
axios.get('/api/user') .then(response => console.log(response.data)) .catch(error => console.error(error));
拿來:
使用 fetch 時,需要明確處理 JSON 解析,這增加了額外的步驟。
fetch('/api/user') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
拿來:
對於 fetch,非 2xx 狀態代碼(如 404 或 500)不會被視為錯誤。您必須手動檢查回應狀態並在需要時拋出錯誤。
fetch('/api/user') .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:
Axios 提供內建攔截器,可讓您全域修改請求或處理回應,這對於新增驗證令牌、日誌記錄等非常有用。
axios.interceptors.request.use(config => { config.headers['Authorization'] = 'Bearer token'; return config; });
拿來:
Fetch 沒有內建攔截器,因此如果需要此行為,您需要手動將 fetch 呼叫包裝在自訂函數中。
axios:
Axios 在發出 POST 請求時會自動將資料字串化,並將 Content-Type 設為 application/json。它還支援輕鬆發送 FormData 等其他格式的資料。
axios.post('/api/user', { name: 'John' });
拿來:
在 fetch 中,您需要手動將資料字串化並設定 POST 請求的標頭。
axios.post('/api/user', { name: 'John' });
axios:
Axios 內建支援使用 CancelToken 取消請求。
axios.post('/api/user', { name: 'John' });
拿來:
使用 fetch,您需要使用 AbortController 來取消請求,這可能會更複雜一些。
axios.post('/api/user', { name: 'John' });
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3