request.js 6.0 KB

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