美文网首页
微信小程序全局请求简单封装

微信小程序全局请求简单封装

作者: 在下高姓 | 来源:发表于2020-10-20 17:11 被阅读0次
GR(method,url,param,callBack){//简单的全局请求封装
    var that = this, 
        data = param|| {}, 
        token =wx.getStorageSync("token");
        method = method.toUpperCase();//小写转大写
        data.access_token=token;
    var requestUrl =this.globalData.http+url;
    //网络请求
    wx.request({
        url: requestUrl,
            data: data,
        method: method, 
        header: {'content-type' : "application/x-www-form-urlencoded"},
        success: res => {
                  if(res.data.error==0){
              callBack(res.data.data);
            }else if(res.data.error==401){//token过期
              wx.removeStorageSync('token')//清除过期token
              wx.removeStorageSync('userinfo')//清除过期token
              wx.getUserInfo({//获取用户信息
                success: function(res1) {
                  wx.login({//获取code
                    success: res2 => {
                      let data={
                        code:res2.code,
                        data: res1.encryptedData,
                        iv: res1.iv,
                      }
                      that.GR('POSt','api/auth/accessToken',data,function(r){
                        wx.setStorageSync("token", r.access_token);
                      })
                    }
                  });
                }
              })
             
            }else {
              that.msg(res.data.message,0)
            }
        },
        fail: (e) => {
            console.log(e);
          
        },
        complete: () => {
          
        }
    })
  },

相关文章

网友评论

      本文标题:微信小程序全局请求简单封装

      本文链接:https://www.haomeiwen.com/subject/umidmktx.html