欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-13 20:12:34
背景 之前小程序代码混乱,所以新项目一开始就准备弄个微信小程序的 request 的封装 httputils.js const request = f...

背景

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

项目地址:

一个 vue + thinkphp5.1 搭建的后台管理:

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