解决登录回环问题

This commit is contained in:
Cheng Zhou
2025-12-18 12:38:04 +08:00
parent 3f955331c9
commit 1ebc706242
11 changed files with 28 additions and 5 deletions
+18 -4
View File
@@ -1,10 +1,13 @@
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus"; import { ElMessage } from "element-plus";
import router from "../router"; import router from "../router";
import { getToken, clearToken } from "../utils/auth"; import { getToken } from "../utils/auth";
import { useAuthStore } from "../store/auth";
import type { ApiError } from "../types/api"; import type { ApiError } from "../types/api";
import { useStudyStore } from "../store/study"; import { useStudyStore } from "../store/study";
let unauthorizedNotified = false;
const instance: AxiosInstance = axios.create({ const instance: AxiosInstance = axios.create({
baseURL: "/", baseURL: "/",
timeout: 15000, timeout: 15000,
@@ -24,6 +27,19 @@ instance.interceptors.response.use(
async (error: AxiosError<ApiError>) => { async (error: AxiosError<ApiError>) => {
const status = error.response?.status; const status = error.response?.status;
const data = error.response?.data; const data = error.response?.data;
// 401 统一处理:同步清理本地 token,并防止重复弹窗
const handleUnauthorized = () => {
const auth = useAuthStore();
auth.logout();
if (!unauthorizedNotified) {
unauthorizedNotified = true;
ElMessage.error(data?.message || "登录已过期,请重新登录");
setTimeout(() => {
unauthorizedNotified = false;
}, 1000);
}
router.push("/login");
};
// 如果当前项目不存在或已失效,清理项目并跳到项目列表 // 如果当前项目不存在或已失效,清理项目并跳到项目列表
if (status === 404 && typeof data?.message === "string" && data.message.toLowerCase().includes("study")) { if (status === 404 && typeof data?.message === "string" && data.message.toLowerCase().includes("study")) {
try { try {
@@ -35,9 +51,7 @@ instance.interceptors.response.use(
router.push("/studies"); router.push("/studies");
} }
if (status === 401) { if (status === 401) {
clearToken(); handleUnauthorized();
ElMessage.error(data?.message || "登录已过期,请重新登录");
router.push("/login");
} else if (data?.message) { } else if (data?.message) {
ElMessage.error(data.message); ElMessage.error(data.message);
} else { } else {
+2 -1
View File
@@ -242,7 +242,8 @@ router.beforeEach(async (to, _from, next) => {
try { try {
await auth.fetchMe(); await auth.fetchMe();
} catch { } catch {
/* ignore */ // token 失效或用户不可用时立即登出,避免重复 401
auth.logout();
} }
} }
if (!to.meta.public && !token) { if (!to.meta.public && !token) {
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
1
/var/lib/postgresql/data
1766032076
5432
/var/run/postgresql
*
52727 0
ready