File size: 1,500 Bytes
5306da4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
import axios from "axios";
const api_url = import.meta.env.VITE_API_URL;
console.log(api_url)
const apiClient = axios.create({
baseURL: api_url,
headers: {
"Content-Type": "application/json",
},
});
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem("authToken");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem("authToken");
window.location.href = "/login";
}
return Promise.reject(error);
}
);
const api = {
get: async (endpoint, config = {}) => {
const response = await apiClient.get(endpoint, { ...config });
return response.data;
},
post: async (endpoint, data, config = {}) => {
const response = await apiClient.post(endpoint, data, { ...config });
return response.data;
},
put: async (endpoint, data, config = {}) => {
const response = await apiClient.put(endpoint, data, { ...config });
return response.data;
},
patch: async (endpoint, data, config = {}) => {
const response = await apiClient.patch(endpoint, data, { ...config });
return response.data;
},
delete: async (endpoint, config = {}) => {
const response = await apiClient.delete(endpoint, { ...config });
return response.data;
},
};
export default api; |