解决登录回环问题

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 { ElMessage } from "element-plus";
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 { useStudyStore } from "../store/study";
let unauthorizedNotified = false;
const instance: AxiosInstance = axios.create({
baseURL: "/",
timeout: 15000,
@@ -24,6 +27,19 @@ instance.interceptors.response.use(
async (error: AxiosError<ApiError>) => {
const status = error.response?.status;
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")) {
try {
@@ -35,9 +51,7 @@ instance.interceptors.response.use(
router.push("/studies");
}
if (status === 401) {
clearToken();
ElMessage.error(data?.message || "登录已过期,请重新登录");
router.push("/login");
handleUnauthorized();
} else if (data?.message) {
ElMessage.error(data.message);
} else {
+2 -1
View File
@@ -242,7 +242,8 @@ router.beforeEach(async (to, _from, next) => {
try {
await auth.fetchMe();
} catch {
/* ignore */
// token 失效或用户不可用时立即登出,避免重复 401
auth.logout();
}
}
if (!to.meta.public && !token) {