49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
import axios from "axios";
|
|
import type {InternalAxiosRequestConfig} from "axios";
|
|
|
|
const baseURL: string = import.meta.env.VITE_API_URL;
|
|
|
|
const apiClient = axios.create({
|
|
baseURL: baseURL,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
export const setAxiosAuthToken = (token: string | null): void => {
|
|
if (token) {
|
|
apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
|
|
} else {
|
|
delete apiClient.defaults.headers.common["Authorization"];
|
|
}
|
|
};
|
|
|
|
apiClient.interceptors.request.use(
|
|
(config: InternalAxiosRequestConfig) => {
|
|
const token = localStorage.getItem("token");
|
|
|
|
if (token && config.headers) {
|
|
config.headers["Authorization"] = `Bearer ${token}`;
|
|
}
|
|
|
|
return config;
|
|
},
|
|
(error: any) => Promise.reject(error),
|
|
);
|
|
|
|
apiClient.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
if (error.response?.status === 401) {
|
|
console.error("Unauthorized - token missing or invalid");
|
|
|
|
localStorage.removeItem("token");
|
|
window.location.href = "/login";
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
export default apiClient;
|