微信小程序HTTP接口请求封装

封装的请求流程大致如下

  • 检查是否有网络,无网络提醒稍候重试

  • 如果有网络发起请求,请求时携带token到header的Authorization中

  • 如果返回数据code==403(认证失败的错误码,根据自己情况改写),则重新进行登录操作

    a. 调用wx.login获取code

    b.调用后台的login接口,登录成功返回token

    c.将token存储到本地

    d.再次发起网络请求

  • 如果返回数据code==0(成功),调用成功回调

  • 其他情况 调用失败回调

var api = require("/config.js").api;


function request({ url, data = '', method = 'POST' }){

    return new Promise((resole,reject)=>{
      wx.getNetworkType({
        success(res) {
          if(res.networkType=="none")
          {
            wx.showToast({
              title: '网络好像不太好哦,请稍候再试',
              icon: "none"
            })
          }
          else 
          {
              wx.request({
                url: api.base_url + url,
                header: {
                  'Authorization': 'Basic ' + wx.getStorageSync('token'),
                  'content-type': 'application/x-www-form-urlencoded' // 默认值
                },
                data: data,
                method: method,
                success(res){
                  if(res.statusCode==403 || res.data.code==403 )
                  {
                      //未登录的处理
                      //认证失败,重新登录
                      wx.showToast({
                        title: '验证失败,自动重试',
                        icon: "none"
                      });
                      wx.removeStorage({
                        key: 'token',
                        success: function(res) {},
                      });
                      wx.login({
                        success: res => {
                          // 发送 res.code 到后台换取 openId, sessionKey, unionId
                          wx.request({
                            url: api.base_url+api.login,
                            header: {
                              'Authorization': 'Basic ' + wx.getStorageSync('token'),
                              'content-type': 'application/x-www-form-urlencoded' // 默认值
                            },
                            data: { code: res.code, invite: wx.getStorageSync('invite')},//带上了用户的邀请id
                            method: "post",
                            success:res=>{
                              
                                  if(res.data.code==0){
                                    wx.setStorageSync('token', res.data.token);
                                    
                                    if (res.data.blgetuserinfo)
                                    {
                                      // 获取用户信息
                                      wx.getSetting({
                                        success: res => {
                                          if (res.authSetting['scope.userInfo']) {
                                            // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
                                            wx.getUserInfo({
                                              success: res => {
                                                // 可以将 res 发送给后台解码出 unionId
                                                this.globalData.userInfo = res.userInfo
                                                //具体实现 这里处理

                                                // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
                                                // 所以此处加入 callback 以防止这种情况
                                                if (this.userInfoReadyCallback) {
                                                  this.userInfoReadyCallback(res)
                                                }
                                              }
                                            })
                                          }
                                        }
                                      })

                                    }

                                    //重新发起请求一次
                                    wx.request({
                                      url: api.base_url + url,
                                      header: {
                                        'Authorization': 'Basic ' + wx.getStorageSync('token'),
                                        'content-type': 'application/x-www-form-urlencoded' // 默认值
                                      },
                                      data: data,
                                      method: method,
                                      success:res=> {
                                        if (res.data.code == 0) {
                                          resole(res);
                                        } else {
                                          reject(res);
                                        }
                                      },
                                      fail:res=>{
                                        reject(res);
                                      }
                                    });

                                  }

                            },
                            fail: res => {
                              reject(res);
                            }
                          })


                        }
                      })
                  }
                  else
                  {
                    if (res.data.code==0) {
                      resole(res);
                    } else {
                      reject(res);
                    }

                  }
                },
                fail: res => {
                  reject(res);
                }
              });

          }
        },

      });

    })
}

module.exports = { request }

在要用到的地方

var http = require("../../utils/http.js");

   http.request({ url:'地址',method:"get"}).then(res=>{
            console.log(res);
          }).catch(res => console.log(res))

 

初稿,供参考~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值