vue下下axios拦截器拦截器token刷新机制的实例代码刷新机制的实例代码
//创建http.js文件,以下是具体代码:
//引入安装的axios插件
import axios from 'axios'
import router from '@/router';
import Vue from 'vue'
const qs = require("qs");
let _this = new Vue();
let isLock = false;
let refreshSubscribers = [];
//判断token是否过期
function isTokenExpired(token) {
let expires_time = JSON.parse(token).expires_time;
let curentTime = new Date().getTime();
if (curentTime >= expires_time) {
return true;
} else {
return false;
}
}
//获取Token对象
function getToken() {
return localStorage.getItem("token");
}
//push所有请求到数组中
function subscribeTokenRefresh(cb) {
refreshSubscribers.push(cb)
}
//刷新请求(refreshSubscribers数组中的请求得到新的token之后会自执行,用新的token去请求数据)
function onRrefreshed(token) {
refreshSubscribers.map(cb => cb(token))
}
//刷新token
function refreshToken(config, token, resolve, reject) {
let data = { refresh_token: JSON.parse(token).refresh_token };
axios({
method: "post",
url: "xxxxxx/refreshToken",//刷新token的接口
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic b3JkZXItc2VydmVyOjEyMzQ1Ng=="
},
data: qs.stringify(data)
}).then(res => {
isLock = false;//释放锁
if (res.data.code === 101) {
_this.$message.error('登录状态已失效,请重新登录。');
localStorage.removeItem("token");
router.push({
path: "/login"
});
return;
}
let expires_time = new Date().getTime() + parseInt(res.data.data.expires_in * 0.8) * 1000;
let token = JSON.parse(localStorage.getItem("token"));
token.expires_time = expires_time;
token.access_token = res.data.data.access_token;
localStorage.setItem("token", JSON.stringify(token));
config.headers.Authorization = 'Bearer ' + res.data.data.access_token;
resolve(config);
//执行数组里的函数,重新发起被挂起的请求
onRrefreshed(res.data.data.access_token)
//清空数组中保存的请求
refreshSubscribers = [] }).catch(err => {
return err;
});