这期内容当中小编将会给大家带来有关如何在微信小程序中封装request ,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
创新互联建站专注于和静企业网站建设,响应式网站,商城系统网站开发。和静网站建设公司,为和静等地区提供建站服务。全流程按需设计,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务
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({//后台请求 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; // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 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"]) {//没授权 showModal('提示', '需要获取用户的权限,点击确定前往设置,打开用户信息', 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 了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。