I am using axios interceptor for refresh token when the access token is expired. Here is my code:
import axios from 'axios'
import jwt_decode from "jwt-decode";
import dayjs from 'dayjs'
const baseURL = 'http://127.0.0.1:8000'
let authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null
const axiosInstance = axios.create({
baseURL,
headers:{Authorization: `Bearer ${authTokens?.access}`}
});
axiosInstance.interceptors.request.use(async req => {
if(!authTokens){
authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null
req.headers.Authorization = `Bearer ${authTokens?.access}`
}
const user = jwt_decode(authTokens.access)
const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1;
if(!isExpired) return req
const response = await axios.post(`${baseURL}/api/token/refresh/`, {
refresh: authTokens.refresh
});
localStorage.setItem('authTokens', JSON.stringify(response.data))
req.headers.Authorization = `Bearer ${response.data.access}`
return req
})
export default axiosInstance;
But I got a problem when calling multiple requests, it goes to an infinite loop. Anyone can help me to fix it. Thanks in advance!
CodePudding user response:
Just use setInterval(() => { your code here })
instead :D
you may see some tutorials like w3schools, etc they always add 0 in the end like : setInterval(() => { do some code }, 0)
but it’s not needed :D because default is 0 :)
CodePudding user response:
I would make the interceptor as response interceptor and not a request interceptor.
axios.interceptors.response.use((response) => {
return response
},
function (error) {
if (error.response.status === 401) {
...fetch token and retry
}