// 引入第三方请求库axios import axios from "axios"; import pinia from "@/store"; import { ElMessage } from "element-plus"; import { removeToken } from "@/utils/auth"; import userStore from "@/store/modules/user"; import router from "@/router"; // 创建axios实例 const server = axios.create({ baseURL: import.meta.env.VITE_APP_BASE_API, timeout: 30000, }); // 创建请求拦截器 server.interceptors.request.use((config) => { const useuserStore = userStore(pinia); config.headers.Authorization = useuserStore.token; config.headers["x-access-token"] = useuserStore.token; return config; }); // 创建相应拦截器 server.interceptors.response.use((response) => { if (response.data.code === 401) { const useuserStore = userStore(pinia); // useuserStore.clearStatus(); // return Promise.reject(response); } if (response.data.code != 200 && response.data.code != 0) { ElMessage.error(response.data.message); return Promise.reject(response); } if (response.data.code === 401) { ElMessage.error(response.data.message); return Promise.reject(response); } if (response.data.code === 412) { ElMessage.error(response.data.message); removeToken(); router.push("/login"); return Promise.reject(response); } return response.data; }); // 暴露axios实例 export default server;