vue2无感刷新token

import axios from ‘axios’
import { Loading, Message, MessageBox } from ‘element-ui’
import { getToken, getRefreshToken, getTokenTimeout, setToken, removeToken, removeRefreshToken, removeTokenTimeout } from ‘./auth’
import { logoutURL, token_baseURL } from ‘./login-request’
import store from “@/store/index”
let loading

function startLoading() {
loading = Loading.service({
lock: true,
text: ‘加载中…’,
background: ‘rgba(0, 0, 0, 0.7)’
})
}

function endLoading() {
loading.close()
}

async function refreshToken(token) {
const refreshUrl = token_baseURL + ‘/authCustom/refreshToken’
let params = new FormData()
params.append(‘refreshToken’, token)
return new Promise((resolve, reject) => {
axios.post(refreshUrl, params, { headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’, ‘isnotToken’: true } }).then(res => {
resolve(res)
})
})
}
function logoutFun() {
removeToken()
removeRefreshToken()
removeTokenTimeout()
window.location.href = logoutURL
}
// 请求拦截
axios.interceptors.request.use(
async (confing) => {

    if (confing.headers.hasOwnProperty('isnotToken') && confing.headers.isnotToken) {
        return confing
    } else {
        confing.cancelToken=new axios.CancelToken(cancel=>{
            store.commit("addCancelToken",cancel)  //切换页面后取消未访问成功的接口
        })
        const hasToken = getToken()
        confing.headers.accessToken = hasToken
        return confing
    }
},
(error) => {
    return Promise.reject(error)
}

)

//响应拦截
let updateTokenTag = true, requestArr = [];
axios.interceptors.response.use(
(response) => {
return response
},
async (error) => {
// 获取状态码
const { status } = error.response
if (error.response.data.code == 401) {
const hasRefreshToken = getRefreshToken()
if (hasRefreshToken) {
if (updateTokenTag) {
updateTokenTag = false;
// 执行更新token接口
const res = await refreshToken(hasRefreshToken)
if (res.status == 200) {
const responseCode = res.data.code
if (responseCode == 200) {
const token = res.data.data
setToken(token)
}
else {
MessageBox.alert(‘Token已失效,请重新登录’, ‘提示’, {
confirmButtonText: ‘确定’,
callback: () => {
logoutFun()
}
});
}
}
// 执行完更新操作 再去执行刚刚并行加入的列队
requestArr.forEach((execute) => execute());
// 置空队列数组
requestArr = [];
updateTokenTag = true;
// 这里是第一次执行进入更新token的接口继续往下执行
const firstApi = await axios.request(error.config);
return Promise.resolve(firstApi);
} else {
// 通过异步将并行的接口加入队列中,等上面更新完token接口再执行队列
return new Promise((resolve) => {
// 用函数的方式将相应数据resolve出去,执行函数就能得到响应结果
requestArr.push(() => {
return resolve(axios.request(error.config));
});
});
}
} else {
logout = true
}

    }
    // 单点登录
    if (status === 416) {
        Message.error({
            message: '您的账号在另一台设备登录,请重新登录...',
            duration: 5000,
            onClose: () => { logoutFun() }
        })
    }
    return Promise.reject(error)
}

)
export default axios

你可能感兴趣的:(javascript,前端,ui)