request.js 6.1 KB

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