小程序登录操作实现

1、登录方法

 //首次登陆验证
  login(){
    console.log("发送了请求")
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code
        const code = res.code;
        //到后台换取 openId
        wx.request({
          url: '服务器地址',
          method: 'post',
          data: {
            code
          },
          success: (res) => {
            console.log(res);
            //取出token
            const token = res.data.token;

            //存储到全局变量中
            this.globalData.token = token;
            //存储到浏览器缓存
            wx.setStorage({
              key: "token",
              data: token,
              success: (res) => {
                console.log(res);
              }
            })

          }
        })


      }
    })
  }

2、验证token方法

//不是首次就应该验证token
  check_token(token){
    console.log("进入了验证")
    wx.request({
      url: '服务器地址',
      method:'post',
      header:{
        token
      },
      success:(res) => {
        if(!res.data.errCode){
          console.log("token有效")
            this.globalData.token = token;
        }else{
          this.login();
        }
      }
    })

  },
   globalData: {
    token:null
  }

3、在小程序加载完毕就调用登录

  onLaunch: function () {
    //从浏览器中取出token
    const token = wx.getStorageSync("token");
    console.log(token);
    //判断是否token是否过期
    if(token && token.length){
      this.check_token(token);
    }else{
      this.login();
    }
    
  }
发布了66 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zlk4524718/article/details/95779847