request.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // 预发布地址
  2. import { apple } from "../config/config";
  3. let httpTrackLog = "https://hyperion-track-app.mokamrp.com";
  4. let httpServiceURL = "";
  5. let version = __wxConfig.envVersion;
  6. import { https } from "../config/config";
  7. switch (version) {
  8. case "develop":
  9. httpServiceURL = https.dev_apiHttps;
  10. break;
  11. case "trial":
  12. httpServiceURL = https.test_apiHttps;
  13. break;
  14. case "release": //正式版
  15. httpServiceURL = https.apiHttps;
  16. break;
  17. default: //未知,默认调用正式版
  18. httpServiceURL = https.apiHttps;
  19. break;
  20. }
  21. // 添加登录锁和请求队列
  22. let isLoggingIn = false;
  23. let loginPromise = null;
  24. let pendingRequests = [];
  25. // 执行等待队列中的请求
  26. const executePendingRequests = () => {
  27. const requests = [...pendingRequests];
  28. pendingRequests = [];
  29. return Promise.all(requests.map((req) => req()));
  30. };
  31. // 普通POST请求
  32. export const post = (url, body = {}) => {
  33. return new Promise((resolve, reject) => {
  34. wx.request({
  35. url: url,
  36. data: body,
  37. method: "POST",
  38. dataType: "json",
  39. success: (res) => {
  40. if (res.statusCode == 200 && res.data.code == 200) {
  41. resolve(res.data.data);
  42. } else {
  43. reject(res);
  44. }
  45. },
  46. fail: (res) => {
  47. console.log(url, "error--------", res);
  48. reject(res);
  49. },
  50. });
  51. });
  52. };
  53. // 普通Get请求
  54. export const get = (url) => {
  55. return new Promise((resolve, reject) => {
  56. wx.request({
  57. url: url,
  58. method: "GET",
  59. success: (res) => {
  60. if (res.statusCode == 200) {
  61. resolve(res.data);
  62. } else {
  63. reject(res);
  64. }
  65. },
  66. fail: (res) => {
  67. reject(res);
  68. },
  69. });
  70. });
  71. };
  72. /**
  73. * 打点请求
  74. */
  75. export function uploadTrackLog(url, body) {
  76. if (!body) {
  77. body = {};
  78. }
  79. return post(httpTrackLog + url, body);
  80. }
  81. export const requestLogin = (data) => {
  82. console.log("开始登录请求,参数:", data);
  83. return new Promise((resolve, reject) => {
  84. // 检查是否已经有token
  85. const existingToken = wx.getStorageSync("accessToken");
  86. if (existingToken) {
  87. console.log("已存在token,跳过登录");
  88. return resolve({ accessToken: existingToken });
  89. }
  90. wx.request({
  91. url: httpServiceURL + "/user/loginWx",
  92. data: data,
  93. method: "POST",
  94. dataType: "json",
  95. header: {},
  96. success: function (res) {
  97. if (res.data.code == 200) {
  98. console.log("登录成功,保存token");
  99. wx.setStorageSync("accessToken", res.data.data.accessToken);
  100. resolve(res.data.data);
  101. } else {
  102. console.log("登录失败,错误信息:", res.data);
  103. wx.showToast({
  104. title: res.data.msg || res.data.error || "登录失败...",
  105. icon: "none",
  106. });
  107. reject(res.data);
  108. }
  109. },
  110. fail: function (res) {
  111. console.log("登录请求失败:", res);
  112. wx.showToast({
  113. title: "登录失败...",
  114. icon: "none",
  115. });
  116. reject(res);
  117. },
  118. });
  119. });
  120. };
  121. export const requestAll = (
  122. requestUrl,
  123. body,
  124. method = "POST",
  125. customHeaders = {},
  126. ) => {
  127. let url = httpServiceURL + requestUrl;
  128. if (method === "GET") {
  129. if (body) {
  130. url += "?";
  131. for (const k in body) {
  132. url += `&${k}=${body[k]}`;
  133. }
  134. }
  135. }
  136. // 封装请求函数
  137. const doRequest = () => {
  138. return new Promise((resolve, reject) => {
  139. const token = wx.getStorageSync("accessToken") || "";
  140. wx.request({
  141. url: url,
  142. data: body,
  143. method: method,
  144. dataType: "json",
  145. header: {
  146. token,
  147. },
  148. success: function (res) {
  149. if (res.data.code == 200) {
  150. if (typeof res.data.data === "number") {
  151. resolve(res.data.data);
  152. } else {
  153. resolve(res.data.data || []);
  154. }
  155. } else if (res.data.code == 20001) {
  156. console.error("令牌过期", url);
  157. reject({ code: 20001, msg: "令牌过期" });
  158. } else {
  159. reject(res.data);
  160. }
  161. },
  162. fail: function (res) {
  163. wx.showToast({
  164. title: "网络出错,请重试...",
  165. icon: "none",
  166. });
  167. reject(res);
  168. },
  169. });
  170. });
  171. };
  172. // 执行请求,如果token过期则重新登录后重试
  173. return doRequest().catch(async (error) => {
  174. if (error.code == 20001) {
  175. // 如果已经在登录中,将请求添加到队列
  176. if (isLoggingIn) {
  177. return new Promise((resolve, reject) => {
  178. pendingRequests.push(() => doRequest().then(resolve).catch(reject));
  179. });
  180. }
  181. // 如果没有在登录,开始登录流程
  182. isLoggingIn = true;
  183. try {
  184. // 使用单例登录Promise
  185. if (!loginPromise) {
  186. wx.removeStorageSync("accessToken");
  187. loginPromise = getApp().login();
  188. }
  189. await loginPromise;
  190. // 重置登录状态和Promise
  191. isLoggingIn = false;
  192. loginPromise = null;
  193. // 执行所有请求
  194. if (pendingRequests.length > 0) {
  195. console.log(wx.getStorageSync("accessToken"));
  196. pendingRequests.push(() => doRequest());
  197. return executePendingRequests();
  198. }
  199. return doRequest();
  200. } catch (loginError) {
  201. // 登录失败,重置状态
  202. isLoggingIn = false;
  203. loginPromise = null;
  204. pendingRequests = [];
  205. console.error("重新登录失败:", loginError);
  206. throw loginError;
  207. }
  208. }
  209. throw error;
  210. });
  211. };
  212. /**
  213. * 添加公共参数
  214. */
  215. export function postWithCommonParams(url, body, method = "POST") {
  216. const app = getApp();
  217. if (!body) {
  218. body = {};
  219. }
  220. if (app.globalData.uuid) {
  221. body.uuid = app.globalData.uuid;
  222. } else {
  223. body.uuid = "fuck";
  224. }
  225. body.gh_id = apple.ghid;
  226. // 判断是否为完整URL
  227. const isFullUrl = url.startsWith("http://") || url.startsWith("https://");
  228. const fullUrl = isFullUrl ? url : https.apiHttps + url;
  229. if (method === "POST") {
  230. return post(fullUrl, body);
  231. } else {
  232. return get(fullUrl);
  233. }
  234. }