Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | 17x 17x 43x 43x 43x 43x 17x | /**
* @file apiClient.ts
* @description
* Configured Axios HTTP client with authentication and error handling.
*
* **Features:**
* - Base URL configuration via environment variable
* - Automatic JWT token attachment from localStorage
* - Request/response logging for debugging
* - 401 Unauthorized token cleanup
* - 2-minute request timeout
*
* **Interceptors:**
* - Request: Attaches Bearer token to Authorization header
* - Response: Logs responses, handles 401 by removing token
*
* **Error Handling:**
* - Logs all API errors
* - Clears token on 401 responses
* - Propagates errors to ErrorBoundary
*
* @module
*/
import axios from 'axios';
/**
* Configured Axios instance for API requests
* @type {import('axios').AxiosInstance}
*/
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8081/api',
timeout: 120000,
});
/**
* Request interceptor: Attach JWT token from localStorage
* Logs request for debugging
*/
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
Iif (token) {
config.headers.Authorization = `Bearer ${token}`;
}
console.log('API Request:', config);
return config;
},
(error) => {
console.error('Request Error:', error);
throw error;
}
);
/**
* Response interceptor: Log responses and handle 401 Unauthorized
* Removes token on 401 and propagates error
*/
apiClient.interceptors.response.use(
(response) => {
console.log('API Response:', response);
return response;
},
(error) => {
console.error('API Error:', error.response?.data || error.message);
// Clear token on unauthorized access
if (error.response?.status === 401) {
localStorage.removeItem('token');
console.warn('Unauthorized access - redirecting to login');
}
throw error;
}
);
export default apiClient;
|