init
This commit is contained in:
58
src/network/axiosSetup.ts
Normal file
58
src/network/axiosSetup.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
// src/services/axiosSetup.ts
|
||||
import axios from 'axios';
|
||||
import dayjs from 'dayjs';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
// Создаем экземпляр axios
|
||||
const api = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
});
|
||||
|
||||
// Устанавливаем токен из localStorage при каждом запуске
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// ===== 🔧 Глобальное преобразование даты (без Z) =====
|
||||
|
||||
const isDate = (value: any): value is Date =>
|
||||
Object.prototype.toString.call(value) === '[object Date]';
|
||||
|
||||
const recursivelyFormatDates = (obj: any): any => {
|
||||
if (obj === null || obj === undefined) return obj;
|
||||
|
||||
if (isDate(obj)) return dayjs(obj).format('YYYY-MM-DDTHH:mm:ss');
|
||||
|
||||
if (Array.isArray(obj)) return obj.map(recursivelyFormatDates);
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [key, recursivelyFormatDates(value)])
|
||||
);
|
||||
}
|
||||
|
||||
return obj;
|
||||
};
|
||||
|
||||
// api.interceptors.request.use((config) => {
|
||||
// if (config.data && typeof config.data === 'object') {
|
||||
// config.data = recursivelyFormatDates(config.data);
|
||||
// }
|
||||
// return config;
|
||||
// }, (error) => Promise.reject(error));
|
||||
|
||||
// ===== 🔐 Перехватчик ответа для проверки 401 =====
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
const router = useRouter();
|
||||
// await router.push('/login');
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default api;
|
||||
Reference in New Issue
Block a user