首先我们需要获取到用户的openid:

onLaunch:function(){
wx.login({
      success: function (res) {
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.ID + '&secret=' + d.Secret + '&js_code=' + res.code + '&grant_type=authorization_code',
          method: 'get',
          success: function (res) {
            that.globalData.openid = res.data.openid;
            console.log("0:"+that.globalData.openid);
            console.log("openid:"+res.data.openid);
            console.log(res);
          }
        })
      }, fail: function (res) {
        reject(res);
      }
    })
}

然后我们去发送请求到后台进行身份验证

onShow:function(){
wx.showToast({
            title:'正在验证身份',
            icon:'loading',
            duration:2500
          });
            wx.request({
            url: "http://localhost/login/"+that.globalData.openid,
            method: 'GET',
            success: function (res) {
              console.log(res);
              if (res.data.code == "200") {
                wx.showToast({
                  title: res.data.msg,
                })
                wx.switchTab({
                  url: '../index/index',
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                })
              }
            }
            });
  }

"坑": 当我们获取到openid后我们会把它存在globaldata中,在请求后台接口时再从globaldata获取openid,但是测试过程中会报一个500:空指针的错误.如果这样直接去请求是不行的,为什么呢?

因为onshow是在onLaunch方法执行后紧接着执行的,但在执行onshow时,可能onlaunch还没来的及把openid赋值到globaldata中,因此此时获取的 openid是空的,所以会报空指针的错误.

解决办法是:

setTimeout(() => {
wx.request({
url:

})}, 3000);

将请求体放在settimeout中,过3秒后在执行,这样就不会再报错了.