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