详解微信小程序的 request 封装示例

(编辑:jimmy 日期: 2024/11/20 浏览:2)

背景

之前小程序代码混乱,所以新项目一开始就准备弄个微信小程序的 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 () {})
        }
       }
      });
     }
    })
   }
  })
 });
};

项目地址:https://github.com/lmxdawn/wxa-demo

一个 vue + thinkphp5.1 搭建的后台管理:https://github.com/lmxdawn/vue-admin-html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。