axios.js 2.2 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: import.meta.env.BASE_URL + "/api",
  12. baseURL: (isNativeApp ? import.meta.env.VITE_PRO_PATH : import.meta.env.VITE_DEV_PATH) + "/api", // 设置 API 基础 URL
  13. timeout: 300000, // 设置请求超时时间
  14. });
  15. const requestState = {
  16. success: [200],
  17. beOverdue: [886],
  18. NotAccessRight: [500],
  19. exception: [400],
  20. };
  21. const pathArr = ["/api/admin/system/login", "/api/logout"];
  22. axiosInstance.interceptors.request.use(
  23. (config) => {
  24. const systemStore = useSystemStore();
  25. systemStore.localLoading(true);
  26. if (!pathArr.includes(config.url)) {
  27. const token = systemStore.token;
  28. if (token && config.headers) {
  29. config.headers["Authorization"] = token;
  30. }
  31. }
  32. return config;
  33. },
  34. (err) => {
  35. const systemStore = useSystemStore();
  36. systemStore.localLoading();
  37. return Promise.reject(err);
  38. }
  39. );
  40. // 响应拦截器
  41. axiosInstance.interceptors.response.use(
  42. (res) => {
  43. const systemStore = useSystemStore();
  44. systemStore.localLoading();
  45. const { code, message: msg } = res.data;
  46. if (requestState.NotAccessRight.includes(code)) {
  47. showNotify({ type: 'warning', message: msg });
  48. return Promise.reject(msg);
  49. }
  50. if (requestState.exception.includes(code)) {
  51. showNotify({ type: 'warning', message: msg });
  52. return Promise.reject(msg);
  53. }
  54. return res.data;
  55. },
  56. (err) => {
  57. const systemStore = useSystemStore();
  58. systemStore.localLoading();
  59. const msg = err.response?.data ? err.response.data.message : "";
  60. showNotify({ type: 'warning', message: msg });
  61. if (requestState.beOverdue.includes( err.status)) {
  62. //
  63. fn_logout();
  64. return undefined;
  65. }
  66. return Promise.reject(err);
  67. }
  68. );
  69. export default axiosInstance;