261a6294cb
* added dynamic configuration of Port in Desktop app * added dynamic configuration of API_URL to docker deployments. Now it works with editing only .env file.
60 lines
1.4 KiB
JavaScript
60 lines
1.4 KiB
JavaScript
import axios from 'axios'
|
|
import { getAPIBaseURL } from './config'
|
|
|
|
// Create API instance without baseURL - will be set dynamically
|
|
const API = axios.create({})
|
|
|
|
let baseURLPromise = null
|
|
let baseURLResolved = false
|
|
|
|
// Get base URL (cached after first call)
|
|
async function ensureBaseURL() {
|
|
if (baseURLResolved) {
|
|
return
|
|
}
|
|
|
|
if (!baseURLPromise) {
|
|
baseURLPromise = getAPIBaseURL()
|
|
}
|
|
|
|
const baseURL = await baseURLPromise
|
|
API.defaults.baseURL = baseURL
|
|
baseURLResolved = true
|
|
}
|
|
|
|
// Request interceptor to add auth token and ensure baseURL is set
|
|
API.interceptors.request.use(
|
|
async (config) => {
|
|
// Ensure baseURL is set before request
|
|
await ensureBaseURL()
|
|
|
|
const token = localStorage.getItem('token')
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
}
|
|
return config
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
// Response interceptor to handle 401 errors
|
|
API.interceptors.response.use(
|
|
(response) => {
|
|
return response
|
|
},
|
|
(error) => {
|
|
if (error.response && error.response.status === 401) {
|
|
// Token is invalid or expired
|
|
console.warn('Authentication failed - token may be expired')
|
|
localStorage.removeItem('token')
|
|
// You might want to redirect to login here
|
|
// window.location.href = '/login'
|
|
}
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
export default API
|