Vue 全局处理访问令牌失效,刷新并重新获取数据
可以在 Vue 的全局配置中,使用 axios 拦截器对请求进行处理。具体步骤如下:
- 在 main.js 中引入 axios 和 vue:
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
- 设置 axios 的拦截器:
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
config.headers.Authorization = localStorage.getItem('token') // 设置请求头中的 token
return config
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response
}, function (error) {
// 对响应错误做点什么
if (error.response.status === 401) { // token 失效
// 发送请求刷新 token
return axios.post('/refreshToken').then(res => {
// 将新的 token 存储到 localStorage 中
localStorage.setItem('token', res.data.token)
// 将原本的请求重新发送
let config = error.config
config.headers.Authorization = res.data.token
return axios.request(config)
}).catch(error => {
// 刷新 token 失败,跳转到登录页
router.replace({
path: '/login',
query: { redirect: router.currentRoute.fullPath }
})
return Promise.reject(error)
})
} else {
return Promise.reject(error)
}
})
- 在需要使用的地方,使用 Vue.prototype.$http 来发送请求:
this.$http.get('/api/data').then(res => {
// 请求成功
}).catch(error => {
// 请求失败
})
原文地址: https://www.cveoy.top/t/topic/otY3 著作权归作者所有。请勿转载和采集!