WXL
2026-08-24 4d6b25bf2f8ef337bf7bf9b22a31b0bade6abd18
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import getConfig from "./config.js";
const { baseURL } = getConfig();
// @/utils/request.js
let isRedirectingToLogin = false;
 
// 全局 SSO 处理标记(挂载到 uni 上,便于跨模块共享)
uni.__isSSOHandling = false;
 
const showToast = (message) => {
  if (uni.$u?.toast) {
    uni.$u.toast(message);
  } else {
    uni.showToast({ title: message, icon: "none" });
  }
};
console.log(baseURL,'baseURL1');
 
const config = {
  baseURL: baseURL,
  timeout: 60000,
  header: {
    "Content-Type": "application/json",
    "X-Business-System": "medical-system",
  },
  loginPage: "/pages/login/Login",
  tokenExpiredCode: 401,
  noPermissionCode: 403,
  whiteList: ["/login", "/getToken", "/GiLink/getCode"],
};
 
const isInWhiteList = (url) => {
  const relativeUrl = url.replace(config.baseURL, "").split("?")[0];
  return config.whiteList.some((path) => {
    if (path.endsWith("/")) return relativeUrl.startsWith(path);
    return relativeUrl === path;
  });
};
 
const navigateToLogin = () => {
  // SSO 处理中,不重复跳转
  if (isRedirectingToLogin || uni.__isSSOHandling) {
    console.log("正在跳转登录页或SSO处理中,跳过");
    return;
  }
 
  isRedirectingToLogin = true;
 
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const isLoginPage =
    currentPage &&
    currentPage.route &&
    currentPage.route.includes("login/Login");
 
  if (isLoginPage) {
    console.log("当前已在登录页,不跳转");
    isRedirectingToLogin = false;
    return;
  }
 
  console.log("跳转到登录页");
  setTimeout(() => {
    uni.redirectTo({
      url:
        config.loginPage +
        "?redirect=" +
        encodeURIComponent(getCurrentPagePath()),
      success: () => {
        console.log("跳转登录页成功");
        isRedirectingToLogin = false;
      },
      fail: () => {
        console.log("跳转登录页失败");
        isRedirectingToLogin = false;
      },
    });
  }, 100);
};
 
const getCurrentPagePath = () => {
  const pages = getCurrentPages();
  return pages[pages.length - 1]?.route || "";
};
 
const checkTokenExpired = (statusCode) => {
  if (statusCode === config.tokenExpiredCode) {
    showToast("登录已过期,请重新登录");
    navigateToLogin();
    return true;
  }
  return false;
};
 
const requestInterceptor = (options) => {
  const token = uni.getStorageSync("token");
 
  if (isInWhiteList(options.url)) {
    console.log("白名单接口,跳过token校验:", options.url);
    return options;
  }
 
  if (!token) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const isLoginPage =
      currentPage &&
      currentPage.route &&
      (currentPage.route.includes("login/Login") ||
        currentPage.route.includes("login/DingTalkLogin"));
 
    if (isLoginPage) {
      console.log("当前是登录页,允许无token请求");
      return options;
    }
 
    console.log("未登录且不在登录页,跳转到登录页");
    navigateToLogin();
    throw new Error("未登录");
  }
 
  options.header = {
    ...options.header,
    Authorization: `Bearer ${token}`,
  };
  return options;
};
 
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  if (checkTokenExpired(statusCode)) return Promise.reject(data);
  if (statusCode === config.noPermissionCode) {
    showToast("无权限访问");
    return Promise.reject(data);
  }
  if (statusCode !== 200) {
    showToast(`请求失败: ${statusCode}`);
    return Promise.reject(data);
  }
  if (data?.code !== 200) {
    showToast(data?.msg || "操作失败");
    return Promise.reject(data);
  }
  return data;
};
 
// 挂起请求队列:认证未完成时暂存请求,完成后批量重试
const pendingQueue = []
let pendingTimer = null
 
function flushPending() {
  clearInterval(pendingTimer)
  pendingTimer = null
  const q = pendingQueue.splice(0)
  q.forEach(({ options, resolve, reject }) => {
    request(options).then(resolve).catch(reject)
  })
}
 
function pendRequest(options) {
  return new Promise((resolve, reject) => {
    pendingQueue.push({ options, resolve, reject })
    if (!pendingTimer) {
      const maxWait = 15000
      const startTime = Date.now()
      pendingTimer = setInterval(() => {
        if (!uni.__authPending || Date.now() - startTime > maxWait) {
          flushPending()
        }
      }, 100)
    }
  })
}
 
const request = async (options) => {
  try {
    // ✅ 认证挂起检查必须在 URL 拼接之前
    //    保存原始 options,重试时避免 baseURL 叠加
    const token = uni.getStorageSync("token");
    if (!token && uni.__authPending && !isInWhiteList(options.url)) {
      return pendRequest({ ...options });  // 传入原始 options 的副本
    }
 
    options = {
      ...config,
      ...options,
      url: config.baseURL + options.url,
      header: { ...config.header, ...options.header },
    };
 
    options = await requestInterceptor(options);
    return new Promise((resolve, reject) => {
      uni.request({
        ...options,
        success: (res) => resolve(responseInterceptor(res)),
        fail: (err) => {
          showToast("网络错误,请重试");
          reject(err);
        },
      });
    });
  } catch (err) {
    return Promise.reject(err);
  }
};
 
const http = {
  get(url, data = {}, options = {}) {
    return request({ url, data, method: "GET", ...options });
  },
  post(url, data = {}, options = {}) {
    return request({ url, data, method: "POST", ...options });
  },
  put(url, data = {}, options = {}) {
    return request({ url, data, method: "PUT", ...options });
  },
  delete(url, data = {}, options = {}) {
    return request({ url, data, method: "DELETE", ...options });
  },
  upload(url, filePath, name = "file", formData = {}) {
    return request({
      url,
      method: "POST",
      filePath,
      name,
      formData,
      header: { "Content-Type": "multipart/form-data" },
    });
  },
};
 
uni.$uapi = http;
export default http;