request.js 6.7 KB

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