indexApi.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 router from "@/routers";
  11. import { cryptoUtil } from "@/utils/crypto";
  12. import { cryptoStrategy } from "@/utils/cryptoStrategy";
  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. const userStore = useUserStore();
  73. axiosCanceler.removePending(config);
  74. config.loading && tryHideFullScreenLoading();
  75. // 解密处理
  76. if (cryptoStrategy.shouldDecrypt(config, headers, data)) {
  77. try {
  78. const decryptedData = cryptoUtil.decrypt(data);
  79. response.data = decryptedData;
  80. } catch (error) {
  81. console.error("解密失败:", error);
  82. ElMessage.error("响应数据解密失败");
  83. return Promise.reject(new Error("响应数据解密失败"));
  84. }
  85. }
  86. const processedData = response.data;
  87. // 登录失效
  88. if (processedData.code == ResultEnum.OVERDUE) {
  89. userStore.setToken("");
  90. router.replace(LOGIN_URL);
  91. ElMessage.error(processedData.msg);
  92. return Promise.reject(processedData);
  93. }
  94. // 全局错误信息拦截(防止下载文件的时候返回数据流,没有 code 直接报错)
  95. if (processedData.code && processedData.code !== ResultEnum.SUCCESS) {
  96. if (!config?.hideBusinessErrorMessage) {
  97. ElMessage.error(processedData.msg);
  98. }
  99. return Promise.reject(processedData);
  100. }
  101. // 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
  102. return processedData;
  103. },
  104. async (error: AxiosError) => {
  105. const { response } = error;
  106. tryHideFullScreenLoading();
  107. // 请求超时 && 网络错误单独判断,没有 response
  108. if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时!请您稍后重试");
  109. if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误!请您稍后重试");
  110. // 根据服务器响应的错误状态码,做不同的处理
  111. if (response && response.data && response.data.message) {
  112. console.log("这里1");
  113. ElMessage.error(response.data.message);
  114. } else {
  115. console.log("这里");
  116. if (response) checkStatus(response.status);
  117. }
  118. // 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
  119. if (!window.navigator.onLine) router.replace("/500");
  120. return Promise.reject(error);
  121. }
  122. );
  123. }
  124. /**
  125. * @description 常用请求方法封装
  126. */
  127. get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  128. return this.service.get(url, { params, ..._object });
  129. }
  130. post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
  131. console.log(config.baseURL, url, params);
  132. return this.service.post(url, params, _object);
  133. }
  134. put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  135. return this.service.put(url, params, _object);
  136. }
  137. delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  138. return this.service.delete(url, { params, ..._object });
  139. }
  140. download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  141. return this.service.post(url, params, { ..._object, responseType: "blob" });
  142. }
  143. }
  144. export default new RequestHttp(config);