前端实现无痛刷新
refresh_token实现无痛刷新import axios from 'axios'import qs from "qs";import Vue from 'vue'import router from './router'import store from '@/store'import { config } from 'shelljs';const baseURL = process.en
·
refresh_token实现无痛刷新
import axios from 'axios'
import qs from "qs";
import Vue from 'vue'
import router from './router'
import store from '@/store'
import { config } from 'shelljs';
const baseURL = process.env.BASE_API
const http = axios.create({
baseURL,
})
let gloableConfig = null;
http.interceptors.request.use(function (config) {
gloableConfig = config;
let _this = this
if (sessionStorage.token) {
config.headers.authorization = sessionStorage.token
}
config.headers['Content-Type'] = "application/json"
const token = sessionStorage.getItem('token')
sessionStorage.setItem('isRouterAlive', true)
if (token) {
let refreshToken = sessionStorage.getItem('refreshToken')
refreshToken = store.commit('refreshToken')
}
return config
}, function (error) {
return Promise.reject(error);
});
// 刷新token 重新加载当前页面请求
function getRefreshTokenAndReload(lastResponse, reload) {
let param = {
accessToken: sessionStorage.getItem('token'),
refreshToken: sessionStorage.getItem('refreshToken')
}
//刷新token 接口
http.post('/user/refreshToken', param).then(res => {
if (res.data.code == '0') {
sessionStorage.setItem("token", res.data.data.accessToken);
sessionStorage.setItem("refreshToken", res.data.data.refreshToken);
reload(lastResponse)
}else{
this.$router.push('/main/login')
}
})
}
// 设置全局捕获错误 拦截器
http.interceptors.response.use((res, data, msg) => {
if (res.data.code == 401002) {
if (router.currentRoute.name !== 'login') {
let reload = undefined
const ret = new Promise((resolve) => {
reload = (response) => {
response.config.url = response.config.url.replace(response.config.baseURL, '');
// 用重新封装的config去请求, 就会将重新请求后的返回
resolve(http(response.config));
}
})
getRefreshTokenAndReload(res, reload)
return ret;
}
}
return res
}, err => {
return Promise.reject(err)
})
export default http
更多推荐
已为社区贡献1条内容
所有评论(0)