axios 簡介
axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:
- 從瀏覽器中創建 XMLHttpRequest
- 從 node.js 發出 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- 自動轉換JSON數據
- 客戶端支持防止 CSRF/XSRF
安裝
npm安裝
$ npm install axios --save
通過cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
發送GET請求
// created:vue生命周期中的鈎子函數,在這個時間點,data中的數據已經注入到響應式系統中 created(){ axios.get('api/getData.php',{ // 還可以直接把參數拼接在url后邊 params:{ title:'眼鏡' } }).then(function(res){ this.goodsList = res.data; }).catch(function (error) { console.log(error); }); }
response.data才是真正返回的后台數據
發送POST請求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // 注意: 如果發送請求時,發現傳遞的參數是對象,那么可用如下方式傳參數 // var params = new URLSearchParams(); // params.append('title', '眼鏡'); // params.append('id',1); // axios.post('/user', params) // .then(function(res){}) // .catch(function(error){});
response.data才是真正返回的后台數據
執行多個並發請求
//獲得用戶信息的請求 function getUserAccount() { return axios.get('/user/12345'); } //獲取用戶許可證的請求 function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all( [ getUserAccount(), getUserPermissions() ] ) .then(axios.spread(function (acct, perms) { //兩個請求現已完成 }) );
請求攔截器和響應攔截器
//請求攔截器 axios.interceptors.request.use( function (config) { // 在發送請求之前做些什么 return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error); } ); //響應攔截器 axios.interceptors.response.use( function (config) { // 對響應數據做點什么 return config; }, function (error) { // 對響應錯誤做點什么 return Promise.reject(error); } );
Vue中axios在發送POST請求時,參數的處理
1. 下載安裝第三方模塊 qs -> npm install qs --save-dev
2. 處理方式
// 第一種: 直接在發送的時候,對數據進行qs.stringify處理 // 缺點: 如果項目大,有大量的請求需要發送,那么一個一個加會很麻煩 axios.post("/checkLogin.php", qs.stringify({ name, pwd })); // 第二種: 使用axios.create創建一個新的axios實例,統一對數據進行處理, 同時也要借助qs模塊 const Axios = axios.create({ baseURL: '/api', transformRequest: [function (data) { const d = qs.stringify(data) return d; }] }) Axios.post("/checkLogin.php", { name, pwd });
作者:雪映月圓
鏈接:https://www.jianshu.com/p/4ee31fdb78b6
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。