您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何在微信小程序中封裝request ,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
httpUtils.js
const request = function (path, method, data, header) { let user_id = ""; let token = ""; try { user_id = wx.getStorageSync(USER_ID_KEY); token = wx.getStorageSync(TOKEN_KEY); } catch (e) {} header = header || {}; let cookie = []; cookie.push("USERID=" + user_id); cookie.push("TOKEN=" + token); cookie.push("device=" + 1); cookie.push("app_name=" + 1); cookie.push("app_version=" + ENV_VERSION); cookie.push("channel=" + 1); header.cookie = cookie.join("; "); return new Promise((resolve, reject) => { wx.request({//后臺(tái)請(qǐng)求 url: API_BASE_URL + path, header: header, method: method, data: data, success: function (res) { if (res.code) { reject(res.data) } else { resolve(res.data) } }, fail: function (res) { reject("not data"); } }); }); };
userLogin.js
const login = function () { try { wx.removeStorageSync(USER_ID_KEY); wx.removeStorageSync(TOKEN_KEY) } catch (e) {} return new Promise((resolve, reject) => { wx.login({ success: res => { let code = res.code; // 已經(jīng)授權(quán),可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會(huì)彈框 wx.getUserInfo({ withCredentials: true, success: res => { let userInfo = res.userInfo; let name = userInfo.nickName; let avatar = userInfo.avatarUrl; let sex = userInfo.gender; let data = { code: code, encryptedData: res.encryptedData, iv: res.iv, name: name, avatar: avatar, sex: sex, from: FROM, }; request("/api/user_login/byWeChatApplet", "POST", data).then( (res)=>{ if (!res.code) { try { wx.setStorageSync(USER_ID_KEY, res.user_id); wx.setStorageSync(TOKEN_KEY, res.token) } catch (e) { reject(JSON.stringify(e)); } } resolve(res) }).catch( (errMsg)=>{ reject(errMsg) }); }, fail: function (res) { if (res.errMsg && res.errMsg.startsWith("getUserInfo:fail") && res.errMsg.search("unauthorized") !== -1) { reject("getUserInfo:fail"); return; } wx.getSetting({ success: (res) => { if (!res.authSetting["scope.userInfo"]) {//沒(méi)授權(quán) showModal('提示', '需要獲取用戶的權(quán)限,點(diǎn)擊確定前往設(shè)置,打開用戶信息', true, function (res) { wx.openSetting({ success: (res) => { // 用戶返回 不管是否開啟 接著去重新登錄 login().then( (res)=>{ if (res.code) { reject(res.message); return } try { wx.setStorageSync(USER_ID_KEY, res.user_id); wx.setStorageSync(TOKEN_KEY, res.token) } catch (e) { reject(JSON.stringify(e)); } resolve(res) }).catch( (errMsg)=>{ reject(errMsg) }); } }) }, function () {}) } } }); } }) } }) }); };
上述就是小編為大家分享的如何在微信小程序中封裝request 了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。