Spaces:
Configuration error
Configuration error
import axios from 'axios'; | |
import { AuthResponse, LoginData, RegisterData, Message } from '../types'; | |
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000'; | |
const api = axios.create({ | |
baseURL: `${API_BASE_URL}/api`, | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
}); | |
// 请求拦截器 - 添加认证token | |
api.interceptors.request.use((config) => { | |
const token = localStorage.getItem('token'); | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}); | |
// 响应拦截器 - 处理认证错误 | |
api.interceptors.response.use( | |
(response) => response, | |
(error) => { | |
if (error.response?.status === 401) { | |
localStorage.removeItem('token'); | |
localStorage.removeItem('user'); | |
window.location.href = '/login'; | |
} | |
return Promise.reject(error); | |
} | |
); | |
export const authAPI = { | |
login: async (data: LoginData): Promise<AuthResponse> => { | |
const response = await api.post('/login', data); | |
return response.data; | |
}, | |
register: async (data: RegisterData): Promise<AuthResponse> => { | |
const response = await api.post('/register', data); | |
return response.data; | |
}, | |
}; | |
export const messageAPI = { | |
getMessages: async (room: string = 'general', limit: number = 50): Promise<Message[]> => { | |
const response = await api.get('/messages', { | |
params: { room, limit } | |
}); | |
return response.data; | |
}, | |
}; | |
export default api; | |