indexLogin.ts 5.9 KB

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