1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import { lastDebounce } from "@/utils/debounce.js" import { useUserStore } from '@/store/index.js' import { recordRequests, retryRequest } from "./refreshToken.js"
const defaultConfig = { url: import.meta.env.VITE_BASE_URL, path: "", params: {}, source: null, loading: true, method: "POST" }
const noRetryAPIs = ["/user/myPage/userInfo", "/user/myPage/login"];
export function http(config) { config = { ...defaultConfig, ...config } console.log('请求拦截:', config); if (!noRetryAPIs.includes(config.path) && !config?.source) { return uni.showToast({ icon: "error", title: 'source 缺失' }); }
return new Promise((resolve, reject) => { if (config?.loading) { uni.showLoading({ title: "加载中", mask: true }); };
uni.request({ header: { Authorization: uni.getStorageSync("Authorization") || "" }, url: (config?.url || defaultConfig.url) + config?.path, method: config?.method || defaultConfig.method, data: config?.params, async success(res) { uni.hideLoading(); console.log('响应拦截:', res.data); if (res.data?.code === 401) { recordRequests(config); lastDebounce(async () => { const userStore = useUserStore(); await userStore.getToken(); retryRequest() }) } if (res.data?.code !== 0 && res.data?.code !== 401) { uni.showToast({ icon: "error", duration: 2000, title: res.data.msg }); } resolve(res.data); }, fail(err) { uni.hideLoading(); uni.reLaunch({ url: "/pages/status/service/error" }) reject(err); }, complete() { } }); }); };
|