indexApi.ts 4.9 KB

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