import axios from 'axios';
import {Message,Loading} from 'element-ui';
import { config } from 'rxjs';
import router from "./router";
let loading;
function startLoading(){
//需要調(diào)用loading的時候調(diào)用
loading=Loading.service({
lock:true,
text:"拼命加載中...",
background: 'rgba(0,0,0,0,7)'
});
}
function endLoading(){
//需要調(diào)用loading的時候調(diào)用
loading.close();
}
//請求攔截
axios.interceptors.request.use(config =>{
//加載動畫時候判斷l(xiāng)ocalStorage是否存在
startLoading();
if(localStorage.eleToken){
//設置統(tǒng)一的請求header
config.headers.Authorization =localStorage.eleToken
}
return config;
},
error =>{
return Promise.reject(error);
}
);
//響應攔截
axios.interceptors.response.use(response =>{
//結(jié)束加載動畫
endLoading();
return response;
},
error =>{
endLoading();
Message.error(error.response.data);
//獲取錯誤狀態(tài)碼
const {status} =error.response;
//401代表token失效
if(status==401){
Message.error("token失效,請重新登陸");
//清除token
localStorage.removeItem('eleToken');
//重新跳轉(zhuǎn)到登陸頁面
router.push('/login');
}
return Promise.reject(error);
});
export default axios;