SocialNetworks_duan/src/utils/http.js
qumeng039@126.com e29d901529 1
2025-08-15 14:49:54 +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) {
if (res.code === 401 || res.code === 403) {
try {
// 尝试刷新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"))
}
} else {
ElMessage({
message: res.message || "Error",
type: "error",
duration: 5 * 1000
})
}
return Promise.reject(new Error(res.message || "Error")) //500会抛出该错
} else {
return res
}
},
(error) => {
ElMessage({
message: error.message,
type: "error",
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service