Created
September 11, 2020 14:20
-
-
Save sagarPakhrin/3c0673328984351639d3c3a98fd7b1ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
const baseURL = process.env.API_URL | |
? process.env.API_URL | |
: "http://127.0.0.1:8000/api/v1/"; | |
const axiosInstance = axios.create({ | |
baseURL: baseURL, | |
timeout: 5000, | |
headers: { | |
Authorization: `Bearer ${localStorage.getItem("access_token")}`, | |
"Content-Type": "application/json", | |
accept: "application/json" | |
} | |
}); | |
axiosInstance.interceptors.response.use( | |
response => response, | |
error => { | |
const originalRequest = error.config; | |
// Prevent infinite loops | |
if ( | |
error.response.status === 401 && | |
originalRequest.url === "auth/token/refresh/" | |
) { | |
console.log("tet"); | |
window.location.href = "auth/signin"; | |
return Promise.reject(error); | |
} | |
if ( | |
error.response.status === 401 && | |
error.response.statusText === "Unauthorized" | |
) { | |
const refresh_token = localStorage.getItem("refresh_token"); | |
return axiosInstance | |
.post("auth/token/refresh/", { refresh: refresh_token }) | |
.then(response => { | |
const access_token = response.data.access; | |
localStorage.setItem("access_token", access_token); | |
axiosInstance.defaults.headers[ | |
"Authorization" | |
] = `Bearer ${access_token}`; | |
originalRequest.headers["Authorization"] = `Bearer ${access_token}`; | |
return axiosInstance(originalRequest); | |
}) | |
.catch(err => { | |
window.location.href = "auth/signin"; | |
}); | |
} | |
return Promise.reject(error); | |
} | |
); | |
export default axiosInstance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment