frontend_nyla/src/api.ts
2025-09-10 07:54:46 +02:00

84 lines
2.8 KiB
TypeScript

// api.ts
import axios from 'axios';
// Utility function to resolve hostname to IP address
const resolveHostnameToIP = async (hostname: string): Promise<string | null> => {
try {
// For localhost, return as is
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return hostname;
}
// For production domains, we can't directly resolve IP due to CORS
// But we can show the hostname which is more useful anyway
return hostname;
} catch (error) {
console.warn('Could not resolve hostname to IP:', error);
return hostname;
}
};
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
withCredentials: true
});
// Add a request interceptor to add the auth token and log backend IP
api.interceptors.request.use(
async (config) => {
// Log backend information
const backendUrl = config.baseURL || import.meta.env.VITE_API_BASE_URL;
console.log(`🌐 Communicating with backend: ${backendUrl}`);
// Try to resolve and log the IP address
if (backendUrl) {
try {
const url = new URL(backendUrl);
const hostname = url.hostname;
const resolvedIP = await resolveHostnameToIP(hostname);
console.log(`📍 Backend hostname: ${hostname}`);
console.log(`🔗 Full backend URL: ${backendUrl}`);
console.log(`🌍 Resolved address: ${resolvedIP}`);
// Log environment info
console.log(`🏗️ Environment: ${import.meta.env.MODE}`);
console.log(`⚙️ API Base URL from env: ${import.meta.env.VITE_API_BASE_URL}`);
} catch (error) {
console.warn('Could not parse backend URL:', error);
}
}
const authData = localStorage.getItem('auth_data');
if (authData) {
try {
const { accessToken, tokenType } = JSON.parse(authData);
if (accessToken) {
config.headers.Authorization = `${tokenType} ${accessToken}`;
}
} catch (error) {
console.error('Error parsing auth data:', error);
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Add a response interceptor to handle token expiration
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
// Clear invalid token
localStorage.removeItem('auth_data');
// Redirect to login
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default api;