utils/request.js
import store from '@/store'
import router from '@/router'
// 全局响应拦截
instance.interceptors.response.use(function (response) {
return response
}, async function (error) {
if (error.response && error.response.status === 401) {
const refreshToken = store.state.tokenInfo.refresh_token
if (refreshToken) {
try {
const result = await axios({
method: 'PUT',
url: 'http://ttapi.research.itcast.cn/app/v1_0/authorizations',
headers: {
Authorization: `Bearer ${refreshToken}`
}
})
const newToken = result.data.data.token
store.commit('setToken', {
refresh_token: refreshToken,
token: newToken
})
// 重新使用我们之间创建的axios实例,用本次错误请求中的配置项,再发一次
return instance(error.config)
} catch {
// 路由跳转,进入登陆页
router.push({
path: '/login',
query: {
// currentRoute:表示当前路由
backto: router.currentRoute.fullPath
}
})
}
} else {
// 路由跳转,进入登陆页
router.push({
path: '/login',
query: {
// currentRoute:表示当前路由
backto: router.currentRoute.fullPath
}
})
}
}
return Promise.reject(error)
})
网友评论