39 lines
910 B
TypeScript
39 lines
910 B
TypeScript
import axios from "axios";
|
|
|
|
const http = axios.create({
|
|
baseURL: process.env.REACT_APP_BACKEND_URL,
|
|
});
|
|
|
|
http.interceptors.request.use((config) => {
|
|
const authToken = localStorage.getItem("authToken");
|
|
if (authToken) {
|
|
config.headers.Authorization = `Bearer ${authToken}`;
|
|
}
|
|
return config;
|
|
});
|
|
|
|
http.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (error.response) {
|
|
const status = error.response.status;
|
|
const requestUrl = error.config.url; // Get the API route
|
|
|
|
// Handle token expiration (401) but NOT for login failures
|
|
if (status === 401 && !requestUrl.includes("/login")) {
|
|
localStorage.removeItem("authToken");
|
|
window.location.href = "/login";
|
|
}
|
|
|
|
// Handle forbidden access
|
|
if (status === 403) {
|
|
localStorage.removeItem("authToken");
|
|
window.location.href = "/login";
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default http;
|