import axios from 'axios'; import {useAuthStore} from "./Stores/auth.js"; window.axios = axios; window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; window.axios.defaults.withCredentials = true // Добавляем токен авторизации к запросам window.axios.interceptors.request.use( (config) => { const authStore = useAuthStore() // Если токен есть, добавляем его в заголовки if (authStore.token) { config.headers.Authorization = `Bearer ${authStore.token}` } // Для форм добавляем заголовок Content-Type if (config.data instanceof FormData) { config.headers['Content-Type'] = 'multipart/form-data' } else { config.headers['Content-Type'] = 'application/json' } return config }, (error) => { return Promise.reject(error) } ) // Интерцептор ответов для обработки ошибок авторизации window.axios.interceptors.response.use( (response) => response, (error) => { const authStore = useAuthStore() console.log('Ошибка в API', error.response) // Если ошибка 401 (Unauthorized) if (error.response?.status === 401) { // Если пользователь был авторизован, выполняем выход if (authStore.isAuthenticated) { authStore.logout() } } // Если ошибка 403 (Forbidden) if (error.response?.status === 403) { console.error('Доступ запрещен:', error.response?.data?.message) } // Если ошибка 422 (Validation Error) if (error.response?.status === 422) { console.log('Ошибки валидации:', error.response?.data?.errors) } return Promise.reject(error) } ) // Вспомогательные методы для работы с API const api = { // GET запрос get: async (url, config = {}) => { try { const response = await axios.get(url, config) return response.data } catch (error) { throw error.response?.data || error } }, // POST запрос post: async (url, data = {}, config = {}) => { try { const response = await axios.post(url, data, config) return response.data } catch (error) { throw error.response?.data || error } }, // PUT запрос put: async (url, data = {}, config = {}) => { try { const response = await axios.put(url, data, config) return response.data } catch (error) { throw error.response?.data || error } }, // PATCH запрос patch: async (url, data = {}, config = {}) => { try { const response = await axios.patch(url, data, config) return response.data } catch (error) { throw error.response?.data || error } }, // DELETE запрос delete: async (url, config = {}) => { try { const response = await axios.delete(url, config) return response.data } catch (error) { throw error.response?.data || error } }, // Загрузка файлов upload: async (url, formData, config = {}) => { try { const response = await axios.post(url, formData, { ...config, headers: { 'Content-Type': 'multipart/form-data' } }) return response.data } catch (error) { throw error.response?.data || error } }, // Проверка токена checkToken: async () => { try { const response = await axios.get('/auth/check-token') return response.data.valid } catch { return false } } } export default api