request.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 = (requestUrl, body, method = 'POST', customHeaders = {}) => {
  122. let url = httpServiceURL + requestUrl;
  123. if (method === 'GET') {
  124. if (body) {
  125. url += '?';
  126. for (const k in body) {
  127. url += `&${k}=${body[k]}`;
  128. }
  129. }
  130. }
  131. // 封装请求函数
  132. const doRequest = () => {
  133. return new Promise((resolve, reject) => {
  134. const token = wx.getStorageSync('accessToken') || '';
  135. wx.request({
  136. url: url,
  137. data: body,
  138. method: method,
  139. dataType: 'json',
  140. header: {
  141. token
  142. },
  143. success: function (res) {
  144. if (res.data.code == 200) {
  145. if (typeof res.data.data === 'number') {
  146. resolve(res.data.data);
  147. } else {
  148. resolve(res.data.data || []);
  149. }
  150. }
  151. else if (res.data.code == 20001) {
  152. reject({ code: 20001, msg: '令牌过期' });
  153. }
  154. else {
  155. reject(res.data);
  156. }
  157. },
  158. fail: function (res) {
  159. wx.showToast({
  160. title: '网络出错,请重试...',
  161. icon: 'none',
  162. });
  163. reject(res);
  164. },
  165. });
  166. });
  167. };
  168. // 执行请求,如果token过期则重新登录后重试
  169. return doRequest().catch(async error => {
  170. if (error.code == 20001) {
  171. // 如果已经在登录中,将请求添加到队列
  172. if (isLoggingIn) {
  173. return new Promise((resolve, reject) => {
  174. pendingRequests.push(() => doRequest().then(resolve).catch(reject));
  175. });
  176. }
  177. // 如果没有在登录,开始登录流程
  178. isLoggingIn = true;
  179. try {
  180. // 使用单例登录Promise
  181. if (!loginPromise) {
  182. wx.removeStorageSync('accessToken');
  183. loginPromise = getApp().login();
  184. }
  185. await loginPromise;
  186. // 重置登录状态和Promise
  187. isLoggingIn = false;
  188. loginPromise = null;
  189. // 执行所有请求
  190. if (pendingRequests.length > 0) {
  191. console.log(wx.getStorageSync('accessToken'))
  192. pendingRequests.push(() => doRequest());
  193. return executePendingRequests();
  194. }
  195. return doRequest();
  196. } catch (loginError) {
  197. // 登录失败,重置状态
  198. isLoggingIn = false;
  199. loginPromise = null;
  200. pendingRequests = [];
  201. console.error('重新登录失败:', loginError);
  202. throw loginError;
  203. }
  204. }
  205. throw error;
  206. });
  207. };
  208. /**
  209. * 添加公共参数
  210. */
  211. export function postWithCommonParams(url, body, method = 'POST') {
  212. const app = getApp()
  213. if (!body) {
  214. body = {}
  215. }
  216. if (app.globalData.uuid) {
  217. body.uuid = app.globalData.uuid
  218. } else {
  219. body.uuid = 'fuck'
  220. }
  221. body.gh_id = apple.ghid
  222. // 判断是否为完整URL
  223. const isFullUrl = url.startsWith('http://') || url.startsWith('https://')
  224. const fullUrl = isFullUrl ? url : https.apiHttps + url
  225. if (method === 'POST') {
  226. return post(fullUrl, body)
  227. } else {
  228. return get(fullUrl)
  229. }
  230. }