// 讀取本地儲存 getUserInfo: function () { return new Promise((resolve, reject) => { wx.getStorage({ key: 'user', success: function (res) { resolve(res.data) }, fail: function (res) { reject('err') } }) }) },
獲取本地緩存
//getUrlImg 解決帶域名或不帶域名的圖片地址 getUrlImg: function ($string) { if (!$string) { return this.imgUrl() + '/uploadfiles/UserFace/no-image.jpg'; } if ($string.indexOf('https://') < 0) { // 不是http開頭的 return this.imgUrl() + $string; } return $string; }, imgUrl: function () { return "這裏放置url" },
// 封裝post請求 post: function (url, data) { return new Promise((resolve, reject) => { //網絡請求 wx.request({ url: url, data: data, method: 'POST', header: { "Content-Type": "application/x-www-form-urlencoded" }, success: function (res) { //服務器返回數據 console.log(data) if (res.statusCode == 200) { if (res.data.code == "NO_LOGIN") { wx.showToast({ title: res.data.msg, icon: 'none', }) wx.removeStorage({ key: 'user', success: function (res) { } }) setTimeout(function () { wx.redirectTo({ url: "/pages/login/login", }) }, 1000) //延遲時間 這裏是1秒 } else { resolve(res); } } else { //返回錯誤提示信息 reject(res.data); } }, error: function (e) { reject('網絡出錯'); } }) }); }, // 封裝get請求 get: function (url, data) { return new Promise((resolve, reject) => { //網絡請求 wx.request({ url: url, data: data, method: 'GET', header: { 'content-type': 'application/json', }, success: function (res) { //服務器返回數據 if (res.statusCode == 200) { if (res.data.code == "NO_LOGIN") { wx.showToast({ title: res.data.msg, icon: 'none', }) wx.removeStorage({ key: 'user', success: function (res) { } }) setTimeout(function () { wx.redirectTo({ url: "/pages/login/login", }) }, 1000) //延遲時間 這裏是1秒 } else { resolve(res); } } else { //返回錯誤提示信息 reject(res.data); } }, complete: function () { reject('網絡出錯'); }, error: function (e) { reject('網絡出錯'); } }) }); },
方便快捷,平時用來進行token 校驗的請求。
使用:
幾個經常使用的封裝函數。每次都要重寫很麻煩。存着php