axios.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import axios from 'axios'
  2. // Create axios instance with base URL
  3. const api = axios.create({
  4. baseURL: import.meta.env.VUE_APP_API_URL || '/api',
  5. timeout: 10000,
  6. headers: {
  7. 'Content-Type': 'application/json'
  8. }
  9. })
  10. // Add response interceptor to handle authentication errors
  11. api.interceptors.response.use(
  12. response => response,
  13. error => {
  14. // Don't log 401 errors for auth status checks (expected when not logged in)
  15. if (error.response && error.response.status === 401 &&
  16. !error.config.url.includes('/auth.php?action=status')) {
  17. console.error('API Error:', error)
  18. }
  19. // Handle 401 Unauthorized responses
  20. if (error.response && error.response.status === 401) {
  21. // Clear any stored auth data
  22. localStorage.removeItem('authToken')
  23. sessionStorage.removeItem('currentUser')
  24. // Emit custom event for app to handle
  25. window.dispatchEvent(new CustomEvent('auth-expired', {
  26. detail: { message: 'Session expired. Please login again.' }
  27. }))
  28. }
  29. return Promise.reject(error)
  30. }
  31. )
  32. export default api