SocialNetworks_duan/src/utils/http.js
qumeng039@126.com 2c9da741cf 解决第二个模块关系图第一次点击不渲染问题
使用watch监听communityNodeList的变化,只要发生改变,就调用initChart函数,并且移除在onMounted中调用initChart
2025-08-15 16:59:01 +08:00

75 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios from "axios"
import cache from "./cache"
import { ElMessage } from "element-plus"
import router from "@/router"
import { useLoginStore } from "@/store/authentication/index"
// 创建axios实例
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_API, // 从环境变量获取基础URL
timeout: 10000, // 请求超时时间
withCredentials: true
})
//白名单
const excludePath = new Set(["/auth/login", "/auth/refresh"])
service.interceptors.request.use(
(config) => {
const token = cache.getItem("token")
if (!excludePath.has(config.url) && token && config.headers) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
async (response) => {
const res = response.data
const loginStore = useLoginStore()
if (res.code !== 200) {
ElMessage({
message: res.message || "Error",
type: "error",
duration: 5 * 1000
})
if (res.code === 401 || res.code === 403) {
try {
// 若token过期或者token无效或者未找到token对页面中需要认证的接口都有效使得重新登录
const refreshed = await loginStore.loginForRefreshToken()
if (refreshed) {
// 刷新成功更新请求头中的accessToken
response.config.headers.Authorization = `Bearer ${loginStore.token}`
return service(response.config) // 重新发送失败的请求
}
} catch (refreshError) {
ElMessage({
message: "会话已过期,请重新登录!",
type: "error",
duration: 5 * 1000
})
cache.removeItem("token")
router.push("/login")
return Promise.reject(new Error("Refresh token failed"))
}
}
return Promise.reject(new Error(res.message || "Error"))
} else {
return res
}
},
async (error) => {
ElMessage({
message: error.message,
type: "error",
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service