69 lines
1.4 KiB
TypeScript
69 lines
1.4 KiB
TypeScript
/**
|
|
* Axios request configuration with authentication
|
|
*/
|
|
import axios from 'axios';
|
|
import { auth } from './auth';
|
|
|
|
const API_BASE_URL = 'http://localhost:8000/api';
|
|
|
|
// Create axios instance
|
|
export const request = axios.create({
|
|
baseURL: API_BASE_URL,
|
|
timeout: 30000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
// Request interceptor - add token to headers
|
|
request.interceptors.request.use(
|
|
(config) => {
|
|
const token = auth.getToken();
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Response interceptor - handle auth errors
|
|
request.interceptors.response.use(
|
|
(response) => {
|
|
return response;
|
|
},
|
|
(error) => {
|
|
if (error.response?.status === 401) {
|
|
// Unauthorized - clear auth and redirect to login
|
|
auth.logout();
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// API functions
|
|
export const authAPI = {
|
|
// Login
|
|
login(username: string, password: string) {
|
|
return request.post('/auth/login', { username, password });
|
|
},
|
|
|
|
// Logout
|
|
logout() {
|
|
return request.post('/auth/logout');
|
|
},
|
|
|
|
// Get current user info
|
|
getCurrentUser() {
|
|
return request.get('/auth/me');
|
|
},
|
|
|
|
// Get user menus
|
|
getMenus() {
|
|
return request.get('/auth/menus');
|
|
},
|
|
};
|