71 lines
1.9 KiB
TypeScript
71 lines
1.9 KiB
TypeScript
import axios from 'axios'
|
|
import { API_CONFIG } from './config'
|
|
|
|
// Create Axios instance with default configuration
|
|
export const apiClient = axios.create({
|
|
baseURL: API_CONFIG.BASE_URL,
|
|
timeout: 10000, // 10 seconds timeout
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
})
|
|
|
|
// Request interceptor to add auth header
|
|
apiClient.interceptors.request.use(
|
|
(config) => {
|
|
// Get token from localStorage
|
|
const token = localStorage.getItem("auth_token")
|
|
|
|
// Add Authorization header if token exists
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
}
|
|
|
|
// Only add static auth header if it has a value (for login requests)
|
|
if (API_CONFIG.AUTH_HEADER && API_CONFIG.AUTH_HEADER.trim()) {
|
|
config.headers.Authorization = API_CONFIG.AUTH_HEADER
|
|
}
|
|
|
|
// Log request for debugging
|
|
console.log('API Request:', {
|
|
method: config.method?.toUpperCase(),
|
|
url: config.url,
|
|
baseURL: config.baseURL,
|
|
fullURL: `${config.baseURL}${config.url}`,
|
|
hasAuthHeader: !!config.headers.Authorization,
|
|
authType: token ? 'Bearer Token' : API_CONFIG.AUTH_HEADER ? 'Static Header' : 'None',
|
|
})
|
|
|
|
return config
|
|
},
|
|
(error) => {
|
|
console.error('Request interceptor error:', error)
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
// Response interceptor for error handling
|
|
apiClient.interceptors.response.use(
|
|
(response) => {
|
|
console.log('API Response:', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
url: response.config.url,
|
|
data: response.data,
|
|
})
|
|
return response
|
|
},
|
|
(error) => {
|
|
console.error('API Error:', {
|
|
status: error.response?.status,
|
|
statusText: error.response?.statusText,
|
|
message: error.message,
|
|
url: error.config?.url,
|
|
data: error.response?.data,
|
|
})
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
export default apiClient
|