85 lines
1.9 KiB
JavaScript
85 lines
1.9 KiB
JavaScript
|
|
// 引入axios
|
|||
|
|
import axios from "axios";
|
|||
|
|
import store from "@/store/index";
|
|||
|
|
import {
|
|||
|
|
showGlobalLoading,
|
|||
|
|
hideGlobalLoading,
|
|||
|
|
} from "@/store/slices/loadingSlice";
|
|||
|
|
const baseURL = import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";
|
|||
|
|
|
|||
|
|
// 全局加载状态loading,基于redux
|
|||
|
|
const handleGlobalLoading = (namespace, type) => {
|
|||
|
|
if (!namespace) return;
|
|||
|
|
store.dispatch(
|
|||
|
|
type === "show"
|
|||
|
|
? showGlobalLoading({ namespace })
|
|||
|
|
: hideGlobalLoading({ namespace })
|
|||
|
|
);
|
|||
|
|
};
|
|||
|
|
// 创建axios实例
|
|||
|
|
const axiosInstance = axios.create({
|
|||
|
|
baseURL, // 基础URL
|
|||
|
|
timeout: 10000, // 请求超时时间
|
|||
|
|
headers: {
|
|||
|
|
"Content-Type": "application/json;charset=utf-8",
|
|||
|
|
},
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 请求拦截器
|
|||
|
|
axiosInstance.interceptors.request.use(
|
|||
|
|
(config) => {
|
|||
|
|
// 开发阶段使用固定的 x-user-id
|
|||
|
|
// 这个ID对应种子数据中的开发默认用户
|
|||
|
|
config.headers["x-user-id"] = "dev-user-id";
|
|||
|
|
|
|||
|
|
// 后续对接飞书后使用token
|
|||
|
|
// const token = localStorage.getItem("token");
|
|||
|
|
// if (token) {
|
|||
|
|
// config.headers["Authorization"] = `Bearer ${token}`;
|
|||
|
|
// }
|
|||
|
|
return config;
|
|||
|
|
},
|
|||
|
|
(error) => {
|
|||
|
|
return Promise.reject(error);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 响应拦截器
|
|||
|
|
axiosInstance.interceptors.response.use(
|
|||
|
|
(response) => {
|
|||
|
|
// 处理响应数据
|
|||
|
|
const res = response.data;
|
|||
|
|
return res;
|
|||
|
|
},
|
|||
|
|
(error) => {
|
|||
|
|
// 处理响应错误
|
|||
|
|
console.error("请求错误:", error);
|
|||
|
|
const message =
|
|||
|
|
error.response?.data?.message || error.message || "网络错误";
|
|||
|
|
return Promise.reject(new Error(message));
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 导出请求方法
|
|||
|
|
export default function request({
|
|||
|
|
url,
|
|||
|
|
apiUrl,
|
|||
|
|
namespace,
|
|||
|
|
method = "get",
|
|||
|
|
data,
|
|||
|
|
params,
|
|||
|
|
headers = {},
|
|||
|
|
}) {
|
|||
|
|
handleGlobalLoading(namespace, "show");
|
|||
|
|
// 返回Promise对象
|
|||
|
|
return axiosInstance({
|
|||
|
|
method,
|
|||
|
|
url: `${apiUrl ? apiUrl : baseURL}${url}`,
|
|||
|
|
data,
|
|||
|
|
params,
|
|||
|
|
headers,
|
|||
|
|
}).finally(() => {
|
|||
|
|
handleGlobalLoading(namespace, "hide");
|
|||
|
|
});
|
|||
|
|
}
|