| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250 |
- // 预发布地址
- import { apple } from '../config/config';
- let httpTrackLog = 'https://hyperion-track-app.mokamrp.com';
- let httpServiceURL = '';
- let version = __wxConfig.envVersion;
- import { https } from '../config/config';
- switch (version) {
- case 'develop':
- httpServiceURL = https.dev_apiHttps;
- break;
- case 'trial':
- httpServiceURL = https.test_apiHttps;
- break;
- case 'release': //正式版
- httpServiceURL = https.apiHttps;
- break;
- default: //未知,默认调用正式版
- httpServiceURL = https.apiHttps;
- break;
- }
- // 添加登录锁和请求队列
- let isLoggingIn = false;
- let loginPromise = null;
- let pendingRequests = [];
- // 执行等待队列中的请求
- const executePendingRequests = () => {
- const requests = [...pendingRequests];
- pendingRequests = [];
- return Promise.all(requests.map(req => req()));
- };
- // 普通POST请求
- export const post = (url, body = {}) => {
- return new Promise((resolve, reject) => {
- wx.request({
- url: url,
- data: body,
- method: 'POST',
- dataType: 'json',
- success: (res) => {
- if (res.statusCode == 200 && res.data.code == 200) {
- resolve(res.data.data);
- } else {
- reject(res);
- }
- },
- fail: (res) => {
- console.log(url, 'error--------', res);
- reject(res);
- },
- });
- });
- };
- // 普通Get请求
- export const get = (url) => {
- return new Promise((resolve, reject) => {
- wx.request({
- url: url,
- method: 'GET',
- success: (res) => {
- if (res.statusCode == 200) {
- resolve(res.data);
- } else {
- reject(res);
- }
- },
- fail: (res) => {
- reject(res);
- },
- });
- });
- };
- /**
- * 打点请求
- */
- export function uploadTrackLog(url, body) {
- if (!body) {
- body = {};
- }
- return post(httpTrackLog + url, body);
- }
- export const requestLogin = (data) => {
- console.log('开始登录请求,参数:', data);
- return new Promise((resolve, reject) => {
- // 检查是否已经有token
- const existingToken = wx.getStorageSync('accessToken');
- if (existingToken) {
- console.log('已存在token,跳过登录');
- return resolve({ accessToken: existingToken });
- }
- wx.request({
- url: httpServiceURL + '/user/loginWx',
- data: data,
- method: 'POST',
- dataType: 'json',
- header: {},
- success: function (res) {
- if (res.data.code == 200) {
- console.log('登录成功,保存token');
- wx.setStorageSync('accessToken', res.data.data.accessToken);
- resolve(res.data.data);
- } else {
- console.log('登录失败,错误信息:', res.data);
- wx.showToast({
- title: res.data.msg || res.data.error || '登录失败...',
- icon: 'none',
- });
- reject(res.data);
- }
- },
- fail: function (res) {
- console.log('登录请求失败:', res);
- wx.showToast({
- title: '登录失败...',
- icon: 'none',
- });
- reject(res);
- },
- });
- });
- };
- export const requestAll = (requestUrl, body, method = 'POST', customHeaders = {}) => {
- let url = httpServiceURL + requestUrl;
- if (method === 'GET') {
- if (body) {
- url += '?';
- for (const k in body) {
- url += `&${k}=${body[k]}`;
- }
- }
- }
- // 封装请求函数
- const doRequest = () => {
- return new Promise((resolve, reject) => {
- // 优先使用传入的token,其次使用storage中的token
- const token = customHeaders.token || wx.getStorageSync('accessToken') || '';
- wx.request({
- url: url,
- data: body,
- method: method,
- dataType: 'json',
- header: {
- ...customHeaders,
- token
- },
- success: function (res) {
- if (res.data.code == 200) {
- if (typeof res.data.data === 'number') {
- resolve(res.data.data);
- } else {
- resolve(res.data.data || []);
- }
- }
- else if(res.data.code==20001){
- reject({code: 20001, msg: '令牌过期'});
- }
- else {
- reject(res.data);
- }
- },
- fail: function (res) {
- wx.showToast({
- title: '网络出错,请重试...',
- icon: 'none',
- });
- reject(res);
- },
- });
- });
- };
- // 执行请求,如果token过期则重新登录后重试
- return doRequest().catch(async error => {
- if (error.code == 20001) {
- // 如果已经在登录中,将请求添加到队列
- if (isLoggingIn) {
- return new Promise((resolve, reject) => {
- pendingRequests.push(() => doRequest().then(resolve).catch(reject));
- });
- }
- // 如果没有在登录,开始登录流程
- isLoggingIn = true;
- try {
- // 使用单例登录Promise
- if (!loginPromise) {
- wx.removeStorageSync('accessToken');
- loginPromise = getApp().login();
- }
- await loginPromise;
-
- // 重置登录状态和Promise
- isLoggingIn = false;
- loginPromise = null;
- // 执行所有请求
- if (pendingRequests.length > 0) {
- pendingRequests.push(() => doRequest());
- return executePendingRequests();
- }
- return doRequest();
- } catch (loginError) {
- // 登录失败,重置状态
- isLoggingIn = false;
- loginPromise = null;
- pendingRequests = [];
- console.error('重新登录失败:', loginError);
- throw loginError;
- }
- }
- throw error;
- });
- };
- /**
- * 添加公共参数
- */
- export function postWithCommonParams(url, body, method = 'POST') {
- const app = getApp()
- if (!body) {
- body = {}
- }
- if (app.globalData.uuid) {
- body.uuid = app.globalData.uuid
- } else {
- body.uuid = 'fuck'
- }
- body.gh_id = apple.ghid
-
- // 判断是否为完整URL
- const isFullUrl = url.startsWith('http://') || url.startsWith('https://')
- const fullUrl = isFullUrl ? url : https.apiHttps + url
-
- if (method === 'POST') {
- return post(fullUrl, body)
- } else {
- return get(fullUrl)
- }
- }
|