indexApi.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
  2. import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
  3. import { ElMessage } from "element-plus";
  4. import { ResultData } from "@/api/interface";
  5. import { ResultEnum } from "@/enums/httpEnum";
  6. import { checkStatus } from "./helper/checkStatus";
  7. import { AxiosCanceler } from "./helper/axiosCancel";
  8. import { useUserStore } from "@/stores/modules/user";
  9. import router from "@/routers";
  10. import { cryptoUtil } from "@/utils/crypto";
  11. import { cryptoStrategy } from "@/utils/cryptoStrategy";
  12. import { applyAuthExpiredSideEffects, isAuthExpiredCode } from "@/api/helper/handleAuthExpired";
  13. export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  14. loading?: boolean;
  15. cancel?: boolean;
  16. encrypt?: boolean; // 是否加密请求参数
  17. /** 业务 code 非成功时不弹出全局 ElMessage,由调用方自行处理 */
  18. hideBusinessErrorMessage?: boolean;
  19. }
  20. const config = {
  21. // 默认地址请求地址,可在 .env.** 文件中修改
  22. baseURL: import.meta.env.VITE_API as string,
  23. // 设置超时时间
  24. timeout: ResultEnum.TIMEOUT as number,
  25. // 跨域时候允许携带凭证
  26. withCredentials: true
  27. };
  28. const axiosCanceler = new AxiosCanceler();
  29. class RequestHttp {
  30. service: AxiosInstance;
  31. public constructor(config: AxiosRequestConfig) {
  32. // instantiation
  33. this.service = axios.create(config);
  34. /**
  35. * @description 请求拦截器
  36. * 客户端发送请求 -> [请求拦截器] -> 服务器
  37. * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
  38. */
  39. this.service.interceptors.request.use(
  40. (config: CustomAxiosRequestConfig) => {
  41. const userStore = useUserStore();
  42. // 重复请求不需要取消,在 api 服务中通过指定的第三个参数: { cancel: false } 来控制
  43. config.cancel ??= true;
  44. config.cancel && axiosCanceler.addPending(config);
  45. // 当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { loading: false } 来控制
  46. config.loading ??= true;
  47. config.loading && showFullScreenLoading();
  48. if (config.headers && typeof config.headers.set === "function") {
  49. config.headers.set("Authorization", userStore.token);
  50. }
  51. // 加密处理
  52. if (cryptoStrategy.shouldEncrypt(config) && config.data) {
  53. try {
  54. config.data = cryptoUtil.encrypt(config.data);
  55. } catch (error) {
  56. return Promise.reject(error);
  57. }
  58. }
  59. return config;
  60. },
  61. (error: AxiosError) => {
  62. return Promise.reject(error);
  63. }
  64. );
  65. /**
  66. * @description 响应拦截器
  67. * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
  68. */
  69. this.service.interceptors.response.use(
  70. (response: AxiosResponse & { config: CustomAxiosRequestConfig }) => {
  71. const { data, config, headers } = response;
  72. axiosCanceler.removePending(config);
  73. config.loading && tryHideFullScreenLoading();
  74. // 解密处理
  75. if (cryptoStrategy.shouldDecrypt(config, headers, data)) {
  76. try {
  77. const decryptedData = cryptoUtil.decrypt(data);
  78. response.data = decryptedData;
  79. } catch (error) {
  80. console.error("解密失败:", error);
  81. ElMessage.error("响应数据解密失败");
  82. return Promise.reject(new Error("响应数据解密失败"));
  83. }
  84. }
  85. const processedData = response.data;
  86. // 登录失效 / 账号在别处登录
  87. if (isAuthExpiredCode(processedData.code)) {
  88. applyAuthExpiredSideEffects(processedData.msg, processedData.code);
  89. return Promise.reject(processedData);
  90. }
  91. // 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
  92. if (processedData.code && processedData.code !== ResultEnum.SUCCESS) {
  93. if (!config?.hideBusinessErrorMessage) {
  94. ElMessage.error(processedData.msg);
  95. }
  96. return Promise.reject(processedData);
  97. }
  98. // 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
  99. return processedData;
  100. },
  101. async (error: AxiosError) => {
  102. const { response } = error;
  103. tryHideFullScreenLoading();
  104. // 请求超时 && 网络错误单独判断,没有 response
  105. if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时!请您稍后重试");
  106. if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误!请您稍后重试");
  107. // 根据服务器响应的错误状态码,做不同的处理
  108. if (response && response.data && response.data.message) {
  109. console.log("这里1");
  110. ElMessage.error(response.data.message);
  111. } else {
  112. console.log("这里");
  113. if (response) checkStatus(response.status);
  114. }
  115. // 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
  116. if (!window.navigator.onLine) router.replace("/500");
  117. return Promise.reject(error);
  118. }
  119. );
  120. }
  121. /**
  122. * @description 常用请求方法封装
  123. */
  124. get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  125. return this.service.get(url, { params, ..._object });
  126. }
  127. post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
  128. console.log(config.baseURL, url, params);
  129. return this.service.post(url, params, _object);
  130. }
  131. put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  132. return this.service.put(url, params, _object);
  133. }
  134. delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  135. return this.service.delete(url, { params, ..._object });
  136. }
  137. download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  138. return this.service.post(url, params, { ..._object, responseType: "blob" });
  139. }
  140. }
  141. export default new RequestHttp(config);