解决登录回环问题
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user