1 import SiteInfo from "../siteInfo.js"; 2 const App = getApp(); 3 const formatTime = date => { 4 const year = date.getFullYear() 5 const month = date.getMonth() + 1 6 const day = date.getDate() 7 const hour = date.getHours() 8 const minute = date.getMinutes() 9 const second = date.getSeconds() 10 return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':') 11 } 12 const formatMD_long = date => { 13 const year = date.getFullYear() 14 const month = date.getMonth() + 1 15 const day = date.getDate() 16 return [year, month, day].join('-') 17 } 18 const formatMD = date => { 19 const month = date.getMonth() + 1 20 const day = date.getDate() 21 return [month, day].join('.') 22 } 23 const formatHM = date => { 24 const hour = date.getHours() 25 const minute = date.getMinutes() 26 return [hour, minute].map(formatNumber).join(':') 27 } 28 29 const formatNumber = n => { 30 n = n.toString() 31 return n[1] ? n : '0' + n 32 } 33 const loadImageError = (e, vm) => { 34 let _errImg = e.target.dataset.errImg; 35 let _objImg = "'" + _errImg + "'"; 36 let _errObj = {}; 37 let _image = e.target.dataset.defaultImage; 38 _errObj[_errImg] = _image; 39 console.error(e.detail.errMsg + "----" + _errObj[_errImg] + "----" + _objImg); 40 vm.setData(_errObj); 41 } 42 const request = opt => { 43 //Location 44 let Location = wx.getStorageSync('location'); 45 delete Location.name; 46 delete Location.address; 47 //Token 48 const Token = wx.getStorageSync('access_token'); 49 //Url 50 const Url = SiteInfo["Siteroot"] + opt.url; 51 wx.request({ 52 url: Url, 53 data: opt.data ? opt.data : {}, 54 header: { 55 Version: SiteInfo["Version"], 56 Authorization: Token, 57 Location: JSON.stringify(Location) 58 }, 59 method: opt.method ? opt.method : "POST", 60 dataType: opt.dataType ? opt.dataType : "json", 61 responseType: opt.responseType ? opt.responseType : "text", 62 success: function (res) { 63 if (res.statusCode == 200) { 64 typeof opt.success == 'function' ? opt.success(res.data) : null;; 65 } else { 66 console.error(`請求發送成功,獲取數據失敗(${opt.url})statusCode ${res.data.status_code} message:${res.data.message}`); 67 if (!App.globalData.userInfoBool) {//!App.globalData.locationBool || 68 console.error(`用戶未受權`); 69 wx.navigateTo({ 70 url: '/pages/openauth/index', //跳轉到受權頁面 71 }) 72 } 73 } 74 }, 75 fail: function (res) { 76 wx.hideLoading(); 77 typeof opt.fail == 'function' ? opt.fail(res) : console.error(`請求發送失敗(${opt.url})`); 78 }, 79 complete: function (res) { 80 setTimeout(function () { 81 wx.hideLoading(); 82 }, 500) 83 typeof opt.complete == 'function' ? opt.complete(res) : null; 84 } 85 }) 86 } 87 let util = { 88 FormatMD_long: formatMD_long, //時間格式:2019-5-1 89 FormatMD: formatMD, //時間格式:5.1 90 FormatHM: formatHM, //時間格式:16:00 91 FormatTime: formatTime, // 時間格式 :2019-02-01 10:22:11 92 LoadImageError: loadImageError,/**圖片加載錯誤 */ 93 Request: request/**請求封裝 */ 94 } 95 export default util
封裝了 request 、時間格式化、圖片加載錯誤json