Files
jiaowu-test/src/utils/request.js

85 lines
1.9 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.

// 引入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");
});
}