45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
// api.ts
|
|
import axios from 'axios';
|
|
|
|
const api = axios.create({
|
|
baseURL: 'https://gateway.poweron-center.net',
|
|
/*baseURL: 'http://localhost:8000',*/
|
|
withCredentials: true
|
|
});
|
|
|
|
// Add a request interceptor to add the auth token
|
|
api.interceptors.request.use(
|
|
(config) => {
|
|
const authData = localStorage.getItem('auth_data');
|
|
if (authData) {
|
|
try {
|
|
const { accessToken, tokenType } = JSON.parse(authData);
|
|
if (accessToken) {
|
|
config.headers.Authorization = `${tokenType} ${accessToken}`;
|
|
}
|
|
} catch (error) {
|
|
console.error('Error parsing auth data:', error);
|
|
}
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Add a response interceptor to handle token expiration
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
if (error.response?.status === 401) {
|
|
// Clear invalid token
|
|
localStorage.removeItem('auth_data');
|
|
// Redirect to login
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|