I have a Vue.js single-page application. My objective is to refresh the token automatically via axios interceptors if it has expired. Before sending a request to the API, I need to check the expiration time of the token. If it has expired, I should refresh it and then proceed with the user's request.
Here is the refresh function I am using:
const refreshToken = () => {
return new Promise((resolve, reject) => {
return axios.post('/api/auth/token/refresh/').then((response) => {
resolve(response)
}).catch((error) => {
reject(error)
})
})
}
And this is the axios request interceptor setup:
axios.interceptors.request.use((config) => {
let originalRequest = config
if (jwt.isTokenExpired()) {
return api.refreshToken()
.then(res => {
if (res.data.error == 'TOKEN_BLACKLISTED' && res.headers.authorization) {
// Extract the token from headers, excluding the "Bearer " prefix
let token = res.headers.authorization.slice(7)
// Save the token in localStorage
jwt.setToken(`"${token}"`)
// Update "Authorization" header with the new token
api.setHeader()
return Promise.resolve(originalRequest)
} else {
jwt.destroyToken()
jwt.destroyExpiredTime()
store.dispatch('auth/destroyToken')
router.push({name: 'login'})
return Promise.reject()
}
})
}
return config
}, (err) => {
return Promise.reject(err)
})
However, there seems to be an issue causing an infinite loop. How can I resolve this?