v0.3
This commit is contained in:
1 parent
d1ee8edbbd
commit
7733a44362
429 files changed
+75840
-94
No files matched your search
@@ -0,0 +1,45 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// 从存储中获取 token
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// 创建 Axios 实例
|
||||
const apiClient = axios.create({
|
||||
//baseURL: window.location.origin,
|
||||
baseURL: 'http://localhost: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;
|
||||
Reference in new issue
Block a user