Vue中axios設置請求和響應攔截


main.js文件添加如下配置:

Vue.prototype.$axios = axios
 
添加請求攔截
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Authorization')) {
console.log("Authorization is true")
config.headers.token = localStorage.getItem('Authorization');// 在發送的請求的header上添加token
}
return config;
},
error => {
console.log("Authorization is false")
return Promise.reject(error);
});

// 添加響應攔截
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
if (error.response) {
switch (error.response.status) {
case 401:
// 返回 401 清除token信息並跳轉到登錄頁面
commit(SET_LOGINTOKEN,"未授權,請登錄");
case 400:
// 返回 401 清除token信息並跳轉到登錄頁面
commit(SET_LOGINTOKEN,"請求錯誤");
case 403:
// 返回 401 清除token信息並跳轉到登錄頁面
commit(SET_LOGINTOKEN,"拒絕訪問");
}
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath}
})
}
  return Promise.reject(error.response.data)
});
 
然后在VUEX里面用axios發送請求,如下:
axios.post(userApiurl,data).then(response =>{});
 
踩坑: main.js里面的配置不變,在vuex中沒有直接使用axios,而是用axios創建了一個其他對象,如下:
const axiosInstance = axios.create({
headers:{'Content-Type':'application/json'},
// 設置傳輸內容的類型和編碼
withCredentials:true // 指定某個請求應該發送憑據
});
再用axiosInstance發送請求的話,main.js里面axios配置沒有在這些請求上生效


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM