import axios from 'axios'; // 从存储中获取 token const token = localStorage.getItem('token'); // 创建 Axios 实例 const apiClient = axios.create({ baseURL: window.location.origin+'/apiForTianze', // 替换为你的后端 API 地址 //baseURL: 'http://192.168.1.21:8080/apiForTianze', // 替换为你的后端 API 地址 //baseURL: 'https://tianzeback.hong.email/apiForTianze', // 替换为你的后端 API 地址 //baseURL: ' http://[2409:8a15:7a47:3d00:43a8:ab66:d726:b52f]:8080/apiForTianze', // 替换为你的后端 API 地址 /* headers: { 'Content-Type': 'application/json' } */ }); apiClient.interceptors.response.use( (response) => response, (error) => { if (error.response && error.response.status === 401) { // token过期或未登录,清空并跳回登录页 localStorage.removeItem('token'); window.location.href = '/login'; } return Promise.reject(error); } ); // 设置默认的 Authorization 头 if (token) { apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`; console.log("Token found and set in headers.",token); } export function setAuthToken(newToken: string | null) { if (newToken) { apiClient.defaults.headers.common['Authorization'] = `Bearer ${newToken}`; localStorage.setItem('token', newToken); console.log("Token updated and set in headers.", newToken); } else { delete apiClient.defaults.headers.common['Authorization']; localStorage.removeItem('token'); console.log("Token removed from headers and localStorage."); } } export default apiClient;