| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 |
- /**
- * 常用方法封装 请求,文件上传等
- * @author echo.
- **/
-
- import pako from './pako.es5.min.js'
- const axg = {
- shopId: function() {
- return "7644106137976965139";
- },
- //接口地址
- interfaceUrl: function() {
- // #ifdef H5
- return '/api';
- // #endif
- // #ifdef MP
- return 'https://tran.jsshuita.cn/dy'
- // return 'http://127.0.0.1:9881/dy'
- // #endif
- },
- toast: function(text, duration, success) {
- // #ifdef APP-PLUS
- plus.nativeUI.toast(text || "出错啦~");
- // #endif
- // #ifndef MP
- uni.showToast({
- title: text || "出错啦~",
- icon: success ? 'success' : 'none',
- duration: duration || 2000
- })
- // #endif
- },
- modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
- uni.showModal({
- title: title || '提示',
- content: content,
- showCancel: showCancel,
- cancelColor: "#555",
- confirmColor: confirmColor || "#5677fc",
- confirmText: confirmText || "确定",
- success(res) {
- if (res.confirm) {
- callback && callback(true)
- } else {
- callback && callback(false)
- }
- }
- })
- },
- isAndroid: function() {
- const res = uni.getSystemInfoSync();
- if(res.platform.toLocaleLowerCase() == 'android')
- {
- return true;
- }
- return false;
- },
- isPhoneX: function() {
- const res = uni.getSystemInfoSync();
- let iphonex = false;
- let models=['iphonex','iphonexr','iphonexsmax','iphone11','iphone11pro','iphone11promax']
- const model=res.model.replace(/\s/g,"").toLowerCase()
- if (models.includes(model)) {
- iphonex = true;
- }
- return iphonex;
- },
- constNum: function() {
- let time = 0;
- // #ifdef APP-PLUS
- time = this.isAndroid() ? 300 : 0;
- // #endif
- return time
- },
- delayed: null,
- decompress(str) {
- try {
- return pako.inflateRaw(axg.base64ToUint8Array(str), {
- to: 'string'
- });
- } catch (error) {
- console.error('解压数据失败:', error);
- throw error;
- }
- },
- base64ToUint8Array(base64String) {
- let padding = '='.repeat((4 - base64String.length % 4) % 4);
- let base64 = (base64String + padding)
- .replace(/\-/g, '+')
- .replace(/_/g, '/');
- let rawData = axg.atob(base64);
- let outputArray = new Uint8Array(rawData.length);
- for (let i = 0; i < rawData.length; ++i) {
- outputArray[i] = rawData.charCodeAt(i);
- }
- return outputArray;
- },
- atob(input) {
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- let str = input.replace(/=+$/, '');
- let output = '';
- if (str.length % 4 === 1) {
- throw new Error('InvalidLengthError');
- }
- for (let i = 0, len = str.length; i < len; i += 4) {
- const a = chars.indexOf(str.charAt(i));
- const b = chars.indexOf(str.charAt(i + 1));
- const c = chars.indexOf(str.charAt(i + 2));
- const d = chars.indexOf(str.charAt(i + 3));
- const sum = (a << 18) | (b << 12) | (c << 6) | d;
- output += String.fromCharCode((sum >> 16) & 0xFF, (sum >> 8) & 0xFF, sum & 0xFF);
- }
-
- return output;
- },
- /**
- * 请求数据处理
- * @param string url 请求地址
- * @param string method 请求方式
- * GET or POST
- * @param {*} postData 请求参数
- * @param bool isDelay 是否延迟显示loading
- * @param bool isForm 数据格式
- * true: 'application/x-www-form-urlencoded'
- * false:'application/json'
- * @param bool hideLoading 是否隐藏loading
- * true: 隐藏
- * false:显示
- */
- request: function(url, method, postData, isDelay, isForm, hideLoading) {
- //接口请求
- let loadding = false;
- axg.delayed && uni.hideLoading();
- clearTimeout(axg.delayed);
- axg.delayed = null;
- if (!hideLoading) {
- axg.delayed = setTimeout(() => {
- uni.showLoading({
- mask: true,
- title: '请求中...',
- success(res) {
- loadding = true
- }
- })
- }, isDelay ? 1000 : 0)
- }
- var header = {
- 'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
- 'authorization': "Bearer "+axg.getToken(),
- 'api-type': "mini"
- }
- // postData.shop = axg.shopId();
-
- return new Promise((resolve, reject) => {
- uni.request({
- url: axg.interfaceUrl() + url,
- data: postData,
- header: header,
- method: method, //'GET','POST'
- dataType: 'json',
- success: (res) => {
- clearTimeout(axg.delayed)
- axg.delayed = null;
- uni.hideLoading()
- if (loadding && !hideLoading) {
- uni.hideLoading()
- }
- if (res.data && res.data.code == 401) {
- uni.showToast({
- title: res.data.msg,
- icon: 'none',
- mask: true,
- duration: 1500,
- success() {
- uni.clearStorageSync();
- uni.navigateTo({
- url:"/pages/auth/login"
- });
- }
- });
- return ;
- }
- if (res.data && res.data.encode) {
- try
- {
- res.data = JSON.parse(axg.decompress(res.data.data));
- }catch(e){
- res.data = axg.decompress(decodeURI(res.data.data));
- }
- }
- resolve(res.data)
- },
- fail: (res) => {
- clearTimeout(axg.delayed)
- axg.delayed = null;
- axg.toast("网络不给力,请稍后再试~")
- reject(res)
- }
- })
- })
- },
- /**
- * 上传文件
- * @param string url 请求地址
- * @param string src 文件路径
- */
- uploadFile: function(url, src, param) {
- return new Promise((resolve, reject) => {
- const uploadTask = uni.uploadFile({
- url: axg.interfaceUrl() + url,
- filePath: src,
- name: 'file',
- header: {
- 'authorization': "Bearer "+axg.getToken(),
- 'platform': "mini",
- 'api-type': "mini"
- },
- formData:param,
- success: function(res) {
- uni.hideLoading()
- console.log(res)
- let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
- if (res.statusCode == 200) {
- //返回图片地址
- let fileObj = d.data;
- resolve(res.data)
- } else {
- axg.toast("系统响应错误");
- }
- },
- fail: function(res) {
- console.log('上传错误:',res)
- reject(res)
- axg.toast(res.msg);
- }
- })
- })
- },
- tuiJsonp: function(url, callback, callbackname) {
- // #ifdef H5
- window[callbackname] = callback;
- let tuiScript = document.createElement("script");
- tuiScript.src = url;
- tuiScript.type = "text/javascript";
- document.head.appendChild(tuiScript);
- document.head.removeChild(tuiScript);
- // #endif
- },
- //设置用户信息
- setUserInfo: function(mobile, token) {
- //uni.setStorageSync("thorui_token", token)
- uni.setStorageSync("user_token", mobile)
- },
- //获取token
- getToken() {
- return uni.getStorageSync("user_token") || 'None'
- },
- //判断是否登录
- isLogin: function() {
- return uni.getStorageSync("user_token") ? true : false
- },
- //跳转页面,校验登录状态
- href(url, isVerify) {
- if (isVerify && !axg.isLogin()) {
- uni.navigateTo({
- url: '/pages/user/login/login'
- })
- } else {
- uni.navigateTo({
- url: url
- });
- }
- }
- }
- export default axg
|