token过期或者失效后,弹窗提示用户登陆失效,重新登陆。
在一些页面中初始化时调了多个API,会出现多次弹出重新登陆的弹框
1、使用axios中的CancelToken,在判断登陆失败时,取消后面的API请求。
2、跳转路由,取消上一个页面未请求成功的API。
const myAxios = { install(Vue) { let http = axios.create({ // baseURL: 'http://localhost:8088/hklms/app', // baseURL: process.env.BASE_API, timeout:1000, // transformRequest: [ // function (data){ // return qs.stringify(data, { // indices: false // }) // } // ] }) http.interceptors.request.use( config => { config.cancelToken = new axios.CancelToken((cancel) => { //使用vuex 定义pushCancel,请求进来存入 store.dispatch('user/pushCancel', {cancelToken:cancel}) }); if (store.state.user.token) { config.headers['token'] = store.state.user.token } return config }, error => { console.log(error) } ) http.interceptors.response.use( response => { const res = response.data; if(res.code && res.code === 401){ store.dispatch('user/clearCancel'); sessionStorage.clear() Message.error(res.msg) router.push("/login") return Promise.reject(error); }else { return response } }, error => { return Promise.reject(error); } )
store中 user.js
state: { axiosCancelArr:[], } mutations:{ CLOSE_SIDEBAR: (state) => { state.opened = !state.opened if(state.opened){ sessionStorage.setItem('sidebarStatus',1) }else { sessionStorage.setItem('sidebarStatus',0) } }, PUSH_CANCEL(state, cancel){ state.axiosCancelArr.push(cancel.cancelToken); }, CLEAR_CANCEL(state){ state.axiosCancelArr.forEach(e=>{ e && e() }); state.axiosCancelArr = [] } }, actions: { pushCancel({commit}, cancel){ commit('PUSH_CANCEL', cancel) }, clearCancel({commit}){ commit('CLEAR_CANCEL'); } }
以上为个人经验,希望对您有所帮助。