解决登录回环问题
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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
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.
@@ -0,0 +1,8 @@
|
||||
1
|
||||
/var/lib/postgresql/data
|
||||
1766032076
|
||||
5432
|
||||
/var/run/postgresql
|
||||
*
|
||||
52727 0
|
||||
ready
|
||||
Reference in New Issue
Block a user