75 lines
2.3 KiB
TypeScript
75 lines
2.3 KiB
TypeScript
import axios, { AxiosInstance } from 'axios';
|
|
|
|
class ApiClient {
|
|
private axiosInstance: AxiosInstance;
|
|
|
|
constructor(baseURL: string = import.meta.env.VITE_API_URL || '/api') {
|
|
this.axiosInstance = axios.create({
|
|
baseURL,
|
|
timeout: 10000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
maxRedirects: 0,
|
|
validateStatus: (status) => status >= 200 && status < 400,
|
|
});
|
|
|
|
this.axiosInstance.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
// Если это редирект (301, 302, 307, 308)
|
|
if (error.response && [301, 302, 307, 308].includes(error.response.status)) {
|
|
const location = error.response.headers.location;
|
|
console.log('🔄 Redirect detected:', location);
|
|
|
|
if (location) {
|
|
// Исправляем HTTP на HTTPS
|
|
let fixedLocation = location;
|
|
if (fixedLocation.startsWith('http://')) {
|
|
fixedLocation = fixedLocation.replace('http://', 'https://');
|
|
console.log('✅ Fixed URL:', fixedLocation);
|
|
}
|
|
|
|
// Повторяем запрос на исправленный URL
|
|
try {
|
|
const response = await this.axiosInstance.get(fixedLocation);
|
|
return response;
|
|
} catch (retryError) {
|
|
return Promise.reject(retryError);
|
|
}
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
|
|
this.axiosInstance.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (error.response?.status === 404) {
|
|
console.error('Resource not found:', error.config?.url);
|
|
} else if (error.response?.status === 500) {
|
|
console.error('Server error:', error.response?.data);
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
}
|
|
|
|
async get<T>(url: string): Promise<{ data: T }> {
|
|
const response = await this.axiosInstance.get<T>(url);
|
|
return { data: response.data };
|
|
}
|
|
|
|
async post<T>(
|
|
url: string,
|
|
data?: any,
|
|
): Promise<{ data: T }> {
|
|
const response = await this.axiosInstance.post<T>(url, data);
|
|
return { data: response.data };
|
|
}
|
|
}
|
|
|
|
export const client = new ApiClient();
|