vue 刷新token 定时刷新token
第一种方法:定时刷新tokenimport { calcDate } from '@/util/date.js'import { getStore } from '@/util/store.js'created() {//实时检测刷新tokenthis.refreshToken()},methods: {// 方法refreshToken() {this.refreshTime = setInte
·
- 第一种方法:定时刷新token
import { calcDate } from '@/util/date.js'
import { getStore } from '@/util/store.js'
created() {
//实时检测刷新token
this.refreshToken()
},
methods: {
// 方法
refreshToken() {
this.refreshTime = setInterval(() => {
const token = getStore({
name: 'token',
debug: true
})
const date = calcDate(token.datetime, new Date().getTime())
if (validatenull(date)) return
if (300 < date.seconds && date.seconds < 600 && !this.refreshLock) {
this.refreshLock = true
this.$store
.dispatch('RefeshToken')
.then(() => {
this.refreshLock = false
})
.catch(() => {
this.refreshLock = false
})
}
}, 10000)
}
}
- 第二种方法:每次请求响应中去刷新token
import { calcDate } from '@/util/date.js'
import { getStore } from '@/util/store.js'
// 用于判断是否刷新
window.isReresh = false
...
//HTTPresponse拦截
axios.interceptors.response.use(
res => {
if (store.getters.token) {
const token = getStore({
name: 'token',
debug: true
})
const date = calcDate(token.datetime, new Date().getTime())
if (date.seconds < 600 && !window.isReresh) {// 小于10分钟则刷新token
window.isReresh = true
store
.dispatch('RefeshToken')
.then(() => {
window.isReresh = false
})
.catch(() => {
window.isReresh = false
})
}
}
return res
},
error => {
// 请求超时处理
if (error.message) {
if (error.message.indexOf('timeout') !== -1) {
Message({
message: '请求超时,请重新刷新页面!',
type: 'error'
})
}
}
if (axios.isCancel(error)) {
console.log('repeated request: ' + error.message)
}
return Promise.reject(new Error(error))
}
)
...
更多推荐
已为社区贡献8条内容
所有评论(0)