Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
axios interceptors usage
import axios from "axios";
const client = axios.create({
baseURL: process.env.BACKEND_API_URL || "hardcoded backend app url",
headers: {
"Content-Type": "application/json",
},
});
client.interceptors.request.use(
(config) => {
let token = localStorage.getItem("accessToken") || "";
config.headers["Authorization"] = `Token ${token}`;
return config;
},
(error) => {
return Promise.reject(error);
}
);
client.interceptors.response.use(
(response) => {
// Any status code that lie within the range of 2xx cause this function to trigger
return response;
},
(error) => {
// Any status codes that falls outside the range of 2xx cause this function to trigger
if (error.response.status == 401) {
localStorage.removeItem("accessToken");
router.push({ name: "login" });
}
return Promise.reject(error);
}
);
export default client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment