- Added axios as a dependency for handling HTTP requests. - Refactored the authentication logic by moving it to a new module structure. - Replaced the old auth store with a composable useAuth for better state management. - Created a new Login.vue component for the login page with improved UI. - Implemented an AuthService for handling authentication-related API calls. - Removed the old Login.vue and uth.ts files to clean up the codebase. - Updated router to use the new login component and auth composable. - Added interceptors to handle token management and error responses globally.
45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
import axios from 'axios';
|
|
import type { InternalAxiosRequestConfig } from 'axios';
|
|
|
|
const api = axios.create({
|
|
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000',
|
|
timeout: 10000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
// Interceptor para agregar el Bearer Token a cada petición
|
|
api.interceptors.request.use(
|
|
(config: InternalAxiosRequestConfig) => {
|
|
const token = localStorage.getItem('auth_token'); // Ajusta según dónde guardes el token
|
|
if (token && config.headers) {
|
|
config.headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Interceptor para manejar errores de forma global
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (error.response) {
|
|
// El servidor respondió con un código de estado fuera del rango 2xx
|
|
console.error(error.response.data);
|
|
|
|
// Manejar error 401 (no autorizado) - redirigir al login
|
|
if (error.response.status === 401) {
|
|
localStorage.removeItem('auth_token');
|
|
localStorage.removeItem('auth_user');
|
|
window.location.href = '/login';
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api; |