Skip to content

Instantly share code, notes, and snippets.

@sagarPakhrin
Created September 11, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagarPakhrin/3c0673328984351639d3c3a98fd7b1ec to your computer and use it in GitHub Desktop.
Save sagarPakhrin/3c0673328984351639d3c3a98fd7b1ec to your computer and use it in GitHub Desktop.
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