request.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /**
  2. * 常用方法封装 请求,文件上传等
  3. * @author echo.
  4. **/
  5. import pako from './pako.es5.min.js'
  6. const axg = {
  7. shopId: function() {
  8. return "7644106137976965139";
  9. },
  10. //接口地址
  11. interfaceUrl: function() {
  12. // #ifdef H5
  13. return '/api';
  14. // #endif
  15. // #ifdef MP
  16. return 'https://tran.jsshuita.cn/v2'
  17. // return 'http://192.168.3.16:9881/v2'
  18. // return 'http://192.168.2.142:9881/v2'
  19. // #endif
  20. },
  21. toast: function(text, duration, success) {
  22. // #ifdef APP-PLUS
  23. plus.nativeUI.toast(text || "出错啦~");
  24. // #endif
  25. // #ifndef MP
  26. uni.showToast({
  27. title: text || "出错啦~",
  28. icon: success ? 'success' : 'none',
  29. duration: duration || 2000
  30. })
  31. // #endif
  32. },
  33. modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
  34. uni.showModal({
  35. title: title || '提示',
  36. content: content,
  37. showCancel: showCancel,
  38. cancelColor: "#555",
  39. confirmColor: confirmColor || "#5677fc",
  40. confirmText: confirmText || "确定",
  41. success(res) {
  42. if (res.confirm) {
  43. callback && callback(true)
  44. } else {
  45. callback && callback(false)
  46. }
  47. }
  48. })
  49. },
  50. isAndroid: function() {
  51. const res = uni.getSystemInfoSync();
  52. if(res.platform.toLocaleLowerCase() == 'android')
  53. {
  54. return true;
  55. }
  56. return false;
  57. },
  58. isPhoneX: function() {
  59. const res = uni.getSystemInfoSync();
  60. let iphonex = false;
  61. let models=['iphonex','iphonexr','iphonexsmax','iphone11','iphone11pro','iphone11promax']
  62. const model=res.model.replace(/\s/g,"").toLowerCase()
  63. if (models.includes(model)) {
  64. iphonex = true;
  65. }
  66. return iphonex;
  67. },
  68. constNum: function() {
  69. let time = 0;
  70. // #ifdef APP-PLUS
  71. time = this.isAndroid() ? 300 : 0;
  72. // #endif
  73. return time
  74. },
  75. delayed: null,
  76. decompress(str) {
  77. try {
  78. return pako.inflateRaw(axg.base64ToUint8Array(str), {
  79. to: 'string'
  80. });
  81. } catch (error) {
  82. console.error('解压数据失败:', error);
  83. throw error;
  84. }
  85. },
  86. base64ToUint8Array(base64String) {
  87. let padding = '='.repeat((4 - base64String.length % 4) % 4);
  88. let base64 = (base64String + padding)
  89. .replace(/\-/g, '+')
  90. .replace(/_/g, '/');
  91. let rawData = axg.atob(base64);
  92. let outputArray = new Uint8Array(rawData.length);
  93. for (let i = 0; i < rawData.length; ++i) {
  94. outputArray[i] = rawData.charCodeAt(i);
  95. }
  96. return outputArray;
  97. },
  98. atob(input) {
  99. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  100. let str = input.replace(/=+$/, '');
  101. let output = '';
  102. if (str.length % 4 === 1) {
  103. throw new Error('InvalidLengthError');
  104. }
  105. for (let i = 0, len = str.length; i < len; i += 4) {
  106. const a = chars.indexOf(str.charAt(i));
  107. const b = chars.indexOf(str.charAt(i + 1));
  108. const c = chars.indexOf(str.charAt(i + 2));
  109. const d = chars.indexOf(str.charAt(i + 3));
  110. const sum = (a << 18) | (b << 12) | (c << 6) | d;
  111. output += String.fromCharCode((sum >> 16) & 0xFF, (sum >> 8) & 0xFF, sum & 0xFF);
  112. }
  113. return output;
  114. },
  115. /**
  116. * 请求数据处理
  117. * @param string url 请求地址
  118. * @param string method 请求方式
  119. * GET or POST
  120. * @param {*} postData 请求参数
  121. * @param bool isDelay 是否延迟显示loading
  122. * @param bool isForm 数据格式
  123. * true: 'application/x-www-form-urlencoded'
  124. * false:'application/json'
  125. * @param bool hideLoading 是否隐藏loading
  126. * true: 隐藏
  127. * false:显示
  128. */
  129. request: function(url, method, postData, isDelay, isForm, hideLoading) {
  130. //接口请求
  131. let loadding = false;
  132. axg.delayed && uni.hideLoading();
  133. clearTimeout(axg.delayed);
  134. axg.delayed = null;
  135. if (!hideLoading) {
  136. axg.delayed = setTimeout(() => {
  137. uni.showLoading({
  138. mask: true,
  139. title: '请求中...',
  140. success(res) {
  141. loadding = true
  142. }
  143. })
  144. }, isDelay ? 1000 : 0)
  145. }
  146. var header = {
  147. 'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
  148. 'authorization': "Bearer "+axg.getToken(),
  149. 'api-type': "mini"
  150. }
  151. // postData.shop = axg.shopId();
  152. return new Promise((resolve, reject) => {
  153. uni.request({
  154. url: axg.interfaceUrl() + url,
  155. data: postData,
  156. header: header,
  157. method: method, //'GET','POST'
  158. dataType: 'json',
  159. success: (res) => {
  160. clearTimeout(axg.delayed)
  161. axg.delayed = null;
  162. uni.hideLoading()
  163. if (loadding && !hideLoading) {
  164. uni.hideLoading()
  165. }
  166. // if (res.data && res.data.code == 401) {
  167. // uni.showToast({
  168. // title: res.data.msg,
  169. // icon: 'none',
  170. // mask: true,
  171. // duration: 1500,
  172. // success() {
  173. // uni.clearStorageSync();
  174. // }
  175. // });
  176. // return ;
  177. // }
  178. if (res.data && res.data.encode) {
  179. try
  180. {
  181. res.data = JSON.parse(axg.decompress(res.data.data));
  182. }catch(e){
  183. res.data = axg.decompress(decodeURI(res.data.data));
  184. }
  185. }
  186. resolve(res.data)
  187. },
  188. fail: (res) => {
  189. clearTimeout(axg.delayed)
  190. axg.delayed = null;
  191. axg.toast("网络不给力,请稍后再试~")
  192. reject(res)
  193. }
  194. })
  195. })
  196. },
  197. /**
  198. * 上传文件
  199. * @param string url 请求地址
  200. * @param string src 文件路径
  201. */
  202. uploadFile: function(url, src, param) {
  203. return new Promise((resolve, reject) => {
  204. const uploadTask = uni.uploadFile({
  205. url: axg.interfaceUrl() + url,
  206. filePath: src,
  207. name: 'file',
  208. header: {
  209. 'authorization': "Bearer "+axg.getToken(),
  210. 'platform': "mini",
  211. 'api-type': "mini"
  212. },
  213. formData:param,
  214. success: function(res) {
  215. uni.hideLoading()
  216. console.log(res)
  217. let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
  218. if (res.statusCode == 200) {
  219. //返回图片地址
  220. let fileObj = d.data;
  221. resolve(res.data)
  222. } else {
  223. axg.toast("系统响应错误");
  224. }
  225. },
  226. fail: function(res) {
  227. console.log('上传错误:',res)
  228. reject(res)
  229. axg.toast(res.msg);
  230. }
  231. })
  232. })
  233. },
  234. tuiJsonp: function(url, callback, callbackname) {
  235. // #ifdef H5
  236. window[callbackname] = callback;
  237. let tuiScript = document.createElement("script");
  238. tuiScript.src = url;
  239. tuiScript.type = "text/javascript";
  240. document.head.appendChild(tuiScript);
  241. document.head.removeChild(tuiScript);
  242. // #endif
  243. },
  244. //设置用户信息
  245. setUserInfo: function(mobile, token) {
  246. //uni.setStorageSync("thorui_token", token)
  247. uni.setStorageSync("user_token", mobile)
  248. },
  249. //获取token
  250. getToken() {
  251. return uni.getStorageSync("user_token") || 'None'
  252. },
  253. //判断是否登录
  254. isLogin: function() {
  255. return uni.getStorageSync("user_token") ? true : false
  256. },
  257. //跳转页面,校验登录状态
  258. href(url, isVerify) {
  259. if (isVerify && !axg.isLogin()) {
  260. uni.navigateTo({
  261. url: '/pages/user/login/login'
  262. })
  263. } else {
  264. uni.navigateTo({
  265. url: url
  266. });
  267. }
  268. }
  269. }
  270. export default axg