index.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
  2. import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
  3. import { LOGIN_URL } from "@/config";
  4. import { ElMessage } from "element-plus";
  5. import { ResultData } from "@/api/interface";
  6. import { ResultEnum } from "@/enums/httpEnum";
  7. import { checkStatus } from "./helper/checkStatus";
  8. import { AxiosCanceler } from "./helper/axiosCancel";
  9. import { useUserStore } from "@/stores/modules/user";
  10. import { localGet } from "@/utils";
  11. import router from "@/routers";
  12. import { cryptoUtil } from "@/utils/crypto";
  13. import { cryptoStrategy } from "@/utils/cryptoStrategy";
  14. export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  15. loading?: boolean;
  16. cancel?: boolean;
  17. encrypt?: boolean; // 是否加密请求参数
  18. /** 业务 code 非成功时不弹出全局 ElMessage,由调用方自行处理 */
  19. hideBusinessErrorMessage?: boolean;
  20. }
  21. const config = {
  22. // 默认地址请求地址,可在 .env.** 文件中修改
  23. baseURL: import.meta.env.VITE_API_URL_PLATFORM as string,
  24. // 设置超时时间
  25. timeout: ResultEnum.TIMEOUT as number,
  26. // 跨域时候允许携带凭证
  27. withCredentials: true
  28. };
  29. const axiosCanceler = new AxiosCanceler();
  30. class RequestHttp {
  31. service: AxiosInstance;
  32. public constructor(config: AxiosRequestConfig) {
  33. // instantiation
  34. this.service = axios.create(config);
  35. /**
  36. * @description 请求拦截器
  37. * 客户端发送请求 -> [请求拦截器] -> 服务器
  38. * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
  39. */
  40. this.service.interceptors.request.use(
  41. (config: CustomAxiosRequestConfig) => {
  42. const userStore = useUserStore();
  43. // 重复请求不需要取消,在 api 服务中通过指定的第三个参数: { cancel: false } 来控制
  44. config.cancel ??= true;
  45. config.cancel && axiosCanceler.addPending(config);
  46. // 当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { loading: false } 来控制
  47. config.loading ??= true;
  48. config.loading && showFullScreenLoading();
  49. if (config.headers && typeof config.headers.set === "function") {
  50. config.headers.set("Authorization", userStore.token);
  51. }
  52. // 加密处理
  53. if (cryptoStrategy.shouldEncrypt(config) && config.data) {
  54. try {
  55. config.data = cryptoUtil.encrypt(config.data);
  56. } catch (error) {
  57. return Promise.reject(error);
  58. }
  59. }
  60. return config;
  61. },
  62. (error: AxiosError) => {
  63. return Promise.reject(error);
  64. }
  65. );
  66. /**
  67. * @description 响应拦截器
  68. * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
  69. */
  70. this.service.interceptors.response.use(
  71. (response: AxiosResponse & { config: CustomAxiosRequestConfig }) => {
  72. const { data, config, headers } = response;
  73. const userStore = useUserStore();
  74. axiosCanceler.removePending(config);
  75. config.loading && tryHideFullScreenLoading();
  76. // 解密处理
  77. if (cryptoStrategy.shouldDecrypt(config, headers, data)) {
  78. try {
  79. const decryptedData = cryptoUtil.decrypt(data);
  80. response.data = decryptedData;
  81. } catch (error) {
  82. console.error("解密失败:", error);
  83. ElMessage.error("响应数据解密失败");
  84. return Promise.reject(new Error("响应数据解密失败"));
  85. }
  86. }
  87. const processedData = response.data;
  88. // 登录失效
  89. if (processedData.code == ResultEnum.OVERDUE) {
  90. userStore.setToken("");
  91. router.replace(LOGIN_URL);
  92. ElMessage.error(processedData.msg);
  93. return Promise.reject(processedData);
  94. }
  95. // 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
  96. if (processedData.code && processedData.code !== ResultEnum.SUCCESS) {
  97. if (!config?.hideBusinessErrorMessage) {
  98. ElMessage.error(processedData.msg);
  99. }
  100. return Promise.reject(processedData);
  101. }
  102. // 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
  103. return processedData;
  104. },
  105. async (error: AxiosError) => {
  106. const { response } = error;
  107. tryHideFullScreenLoading();
  108. // 请求超时 && 网络错误单独判断,没有 response
  109. if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时!请您稍后重试");
  110. if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误!请您稍后重试");
  111. // 根据服务器响应的错误状态码,做不同的处理
  112. if (response.data.message) {
  113. ElMessage.error(response.data.message);
  114. } else {
  115. if (response) checkStatus(response.status);
  116. }
  117. // 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
  118. if (!window.navigator.onLine) router.replace("/500");
  119. return Promise.reject(error);
  120. }
  121. );
  122. }
  123. /**
  124. * @description 常用请求方法封装
  125. */
  126. get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  127. return this.service.get(url, { params, ..._object });
  128. }
  129. post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
  130. console.log(config.baseURL, url, params);
  131. return this.service.post(url, params, _object);
  132. }
  133. put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  134. return this.service.put(url, params, _object);
  135. }
  136. delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  137. return this.service.delete(url, { params, ..._object });
  138. }
  139. download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  140. return this.service.post(url, params, { ..._object, responseType: "blob" });
  141. }
  142. /**
  143. * @description 文件上传方法(基于 XMLHttpRequest)
  144. * @param url 上传地址
  145. * @param formData FormData 对象
  146. * @param onProgress 上传进度回调函数 (progress: number) => void
  147. * @param baseURL 可选的基础URL,不传则使用默认baseURL
  148. * @returns Promise<ResultData<T>>
  149. */
  150. upload<T = any>(
  151. url: string,
  152. formData: FormData,
  153. onProgress?: (progress: number) => void,
  154. baseURL?: string
  155. ): Promise<ResultData<T>> {
  156. return new Promise((resolve, reject) => {
  157. const xhr = new XMLHttpRequest();
  158. const userStore = useUserStore();
  159. // 如果传入了 baseURL,使用传入的 baseURL;如果 URL 是完整 URL(以 http 开头),直接使用;否则使用默认 baseURL
  160. const fullUrl = baseURL ? `${baseURL}${url}` : url.startsWith("http") ? url : `${config.baseURL}${url}`;
  161. // 监听上传进度
  162. if (onProgress) {
  163. xhr.upload.addEventListener("progress", e => {
  164. if (e.lengthComputable) {
  165. const percentComplete = Math.round((e.loaded / e.total) * 100);
  166. onProgress(percentComplete);
  167. }
  168. });
  169. }
  170. // 监听请求完成
  171. xhr.addEventListener("load", () => {
  172. if (xhr.status >= 200 && xhr.status < 300) {
  173. try {
  174. const response = JSON.parse(xhr.responseText);
  175. // 统一处理响应,与 axios 拦截器保持一致
  176. if (response.code == ResultEnum.OVERDUE) {
  177. userStore.setToken("");
  178. router.replace(LOGIN_URL);
  179. ElMessage.error(response.msg);
  180. reject(response);
  181. return;
  182. }
  183. if (response.code && response.code !== ResultEnum.SUCCESS) {
  184. ElMessage.error(response.msg);
  185. reject(response);
  186. return;
  187. }
  188. resolve(response);
  189. } catch (error) {
  190. reject(new Error("响应解析失败"));
  191. }
  192. } else {
  193. const errorMsg = `上传失败: ${xhr.status} ${xhr.statusText}`;
  194. ElMessage.error(errorMsg);
  195. reject(new Error(errorMsg));
  196. }
  197. });
  198. // 监听请求错误
  199. xhr.addEventListener("error", () => {
  200. const errorMsg = "网络错误!请您稍后重试";
  201. ElMessage.error(errorMsg);
  202. reject(new Error(errorMsg));
  203. });
  204. // 监听请求中止
  205. xhr.addEventListener("abort", () => {
  206. reject(new Error("上传已取消"));
  207. });
  208. // 打开请求
  209. xhr.open("POST", fullUrl, true);
  210. // 设置请求头
  211. const token = userStore.token || localGet("geeker-user")?.token;
  212. if (token) {
  213. xhr.setRequestHeader("Authorization", token);
  214. }
  215. // 设置超时
  216. xhr.timeout = config.timeout;
  217. xhr.addEventListener("timeout", () => {
  218. const errorMsg = "请求超时!请您稍后重试";
  219. ElMessage.error(errorMsg);
  220. reject(new Error(errorMsg));
  221. });
  222. // 发送请求
  223. xhr.withCredentials = config.withCredentials;
  224. xhr.send(formData);
  225. });
  226. }
  227. }
  228. export default new RequestHttp(config);