axios.Im.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import axios from "axios";
  2. import { Capacitor } from '@capacitor/core';
  3. import { showNotify } from 'vant';
  4. import { useSystemStore } from "@/stores/modules/systemStore";
  5. import { fn_logout } from "@/utils";
  6. // 用于存储请求和对应的 AbortController
  7. const requestMap = new Map();
  8. const requestCountMap = new Map(); // 用于记录请求的次数
  9. const isNativeApp = Capacitor.isNativePlatform();
  10. const axiosInstance = axios.create({
  11. baseURL: (isNativeApp ? import.meta.env.VITE_PRO_IM_PATH : import.meta.env.VITE_DEV_IM_PATH) + "/api/v1", // 设置 API 基础 URL
  12. timeout: 300000, // 设置请求超时时间
  13. });
  14. const requestState = {
  15. success: [200],
  16. beOverdue: [886],
  17. NotAccessRight: [500],
  18. exception: [400],
  19. };
  20. const pathArr = ["/api/admin/system/login", "/api/logout"];
  21. axiosInstance.interceptors.request.use(
  22. (config) => {
  23. const systemStore = useSystemStore();
  24. systemStore.localLoading(true);
  25. if (!pathArr.includes(config.url)) {
  26. const token = localStorage.getItem("token");
  27. if (token && config.headers) {
  28. config.headers["Authorization"] = token;
  29. }
  30. }
  31. return config;
  32. },
  33. (err) => {
  34. const systemStore = useSystemStore();
  35. systemStore.localLoading();
  36. return Promise.reject(err);
  37. }
  38. );
  39. // 响应拦截器
  40. axiosInstance.interceptors.response.use(
  41. (res) => {
  42. const systemStore = useSystemStore();
  43. systemStore.localLoading();
  44. const { code, message: msg } = res.data;
  45. if (requestState.NotAccessRight.includes(code)) {
  46. // showNotify({ type: 'warning', message: msg });
  47. return Promise.reject(msg);
  48. }
  49. if (requestState.exception.includes(code)) {
  50. // showNotify({ type: 'warning', message: msg });
  51. return Promise.reject(msg);
  52. }
  53. return res.data;
  54. },
  55. (err) => {
  56. const systemStore = useSystemStore();
  57. systemStore.localLoading();
  58. const msg = err.response?.data ? err.response.data.message : "";
  59. // showNotify({ type: 'warning', message: msg });
  60. if (requestState.beOverdue.includes( err.status)) {
  61. //
  62. fn_logout();
  63. return undefined;
  64. }
  65. return Promise.reject(err);
  66. }
  67. );
  68. export default axiosInstance;