Axios 是一個基于 Promise 的 HTTP 客戶端,用于瀏覽器和 node.js 環境。它提供了一種簡單易用的方式來發送 HTTP 請求,并支持諸如請求和響應攔截、轉換數據、取消請求以及自動轉換 JSON 數據等功能。
Axios 名字的由來
Axios 的名字來源于希臘神話中的英雄 Axios。這位英雄是一個勇敢的冒險家,擁有強大的力量和知識,能夠改變任何事物,使它們變得更加強大。Axios 庫的設計初衷和命名靈感正是源自于這位英雄,旨在提供一種強大且靈活的 HTTP 客戶端,幫助開發者在前端和 Node.js 環境中輕松發送 HTTP 請求,并處理各種復雜的網絡交互場景。
Axios 詳細介紹
-
基本概念
- Axios(全稱 ajax I/O system)不是一種新技術,本質上是對原生 XHR(XMLHttpRequest)的封裝,但它是基于 Promise 的實現版本,符合最新的 ES 規范。
- Axios 提供了簡單而直觀的 API,使得在前端應用程序中進行 HTTP 通信變得更加容易。
- Axios 可以與現代前端框架(如 React、Vue.js 和 Angular)以及后端服務器(如 Node.js)配合使用。
-
主要特性
- 從瀏覽器中創建 XMLHttpRequests。
- 從 node.js 創建 http 請求。
- 支持 Promise API。
- 攔截請求和響應。
- 轉換請求數據和響應數據。
- 取消請求。
- 自動轉換 JSON 數據。
- 客戶端支持防御 XSRF。
Axios 安裝
Axios 可以通過多種方式進行安裝,包括使用 npm、yarn 或 CDN。
- 使用 npm
npm install axios
- 使用 yarn
yarn add axios
- 使用 CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios 示例
1. 發送 GET 請求
- 基本用法
axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 或者使用 axios(config) 形式
axios({ method: 'get', url: '/user', params: { ID: 12345 }
})
.then(function (response) { console.log(response);
})
.catch(function (error) { console.log(error);
});
- 使用 axios 實例
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'}
}); // 發送請求
instance.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2. 發送 POST 請求
- application/json 類型
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
- form-data 類型
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('user', '12345'); axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3 請求攔截器和響應攔截器
- 請求攔截器
axios.interceptors.request.use(function (config) { // 在發送請求之前做些什么 return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); });
- 響應攔截器
axios.interceptors.response.use(function (response) { // 對響應數據做點什么 return response; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); });
- Axios 官方站點: https://axios-http.com/zh/
- Axios 源碼地址:https://github.com/axios/axios