微信小程序使用session(详细、亲测有效)

本文详细描述了解决微信小程序中session不唯一问题的步骤,包括获取登录请求的Set-Cookie,存储在本地缓存,以及如何在每次请求中加入Cookie。重点介绍了登录流程和如何确保会话一致性。
摘要由CSDN通过智能技术生成

1、背景

        解决微信小程序session不能使用,session 不唯一问题。

        操作流程

1.调用登录请求

2.获取登录请求中的set-cookie 信息

3. 保存到本地缓存

4.每次调用加入请求头中

       例如: 微信小程序调用用户信息。

       login. wxml

  <button bindtap="getUserInfo">getUserInfo</button>

         login.js

getUserInfo(){
    // 获取用户信息
    httpUtils.request({
      showLoading: true,
      url: `/user/get/login`,
      message: "正在获取用户数据..."
    }).then(res => {
      this.setData(
        res.data.data
      )
      ui.showToast(res.data.errorMsg)
    }).catch(err => {
      console.log('ERROR')
    });
  },

   控制台显示未登录44dc2dde48b8409ba6b48ebd3e416c86.png

发现后台没有session传入

076c8419e5e94b3eb747d3dc2c9cbfdb.png

2、步骤

        2.1首次请求

                首次请求获取 header 中的Set-Cookie 作为cookie信息

0e3aa109814744dc9675fe5d59ffcc1e.png

  直接开始登录流程

    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          //发起网络请求
          httpUtils.request({
            method: "GET", showLoading: true,url: `/wx/user/wxLogin`,message: "正在登录",
           data: {
              code: res.code
            }
          }).then(res => {
            if(res.header["Set-Cookie"]){
              wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
             }
             this.globalData.userInfo = res.data.data
            ui.showToast(res.data.errorMsg)
          }).catch(err => {
            console.log('ERROR')
          });
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })

   注意:每次重新登录前要删除缓存信息

        wx.removeStorageSync('sessionid') 

        2.2存入微信小程序缓存

if(res.header["Set-Cookie"]){
   wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
}

           8f957a7b6b514384a4fa85026d42763e.pngSESSION=MjMxZDM3NmYtYzgzYy00NDc0LWExODYtOWRmODI0N2M1NTMy; Path=/api; HttpOnly; SameSite=Lax

        2.3将cookie加入请求头

let header = {
      'content-type': 'application/json', // 默认值
    }
    let session_id = wx.getStorageSync('sessionid');//本地取存储的sessionID
    if (session_id != "" && session_id != null) { //本地session存在,则放到header里
      header.Cookie = session_id;
    }

        2.4请求

                最后直接使用wx.request  API调用接口,大功告成。

           重新调用后0c054abe98074257a4767de12fb4a2bb.png

 0162930ac51f4105940f7a6dd0e3dd38.png

附录

httpUtils.js

const ui = require('./ui');
const BASE_URL = 'http://XXXXXX:8890/api'

/**
 * 网络请求request
 * obj.data 请求接口需要传递的数据
 * obj.showLoading 控制是否显示加载Loading 默认为false不显示
 * obj.contentType 默认为 application/json
 * obj.method 请求的方法  默认为GET
 * obj.url 请求的接口路径 
 * obj.message 加载数据提示语
 */
function request(obj) {
  return new Promise(function (resolve, reject) {
    if (obj.showLoading) {
      ui.showLoading(obj.message ? obj.message : '加载中...');
    }
    var data = {};
    if (obj.data) {
      data = obj.data;
    }
    var contentType = 'application/json';
    if (obj.contentType) {
      contentType = obj.contentType;
    }

    var method = 'GET';
    if (obj.method) {
      method = obj.method;
    }

    let header = {
      'content-type': 'application/json', // 默认值
    }
    let session_id = wx.getStorageSync('sessionid');//本地取存储的sessionID
    if (session_id != "" && session_id != null) { //本地session存在,则放到header里
      header.Cookie = session_id;
    }

    wx.request({
      url: BASE_URL + obj.url,
      data: data,
      method: method,
      //添加请求头
      header: header,
      contentType: contentType,
      //请求成功
      success: function (res) {
        console.log('===========================================================================================')
        console.log('==    接口地址:' + obj.url);
        console.log('==    接口参数:' + JSON.stringify(data));
        console.log('==    请求类型:' + method);
        console.log("==    接口状态:" + res.statusCode);
        console.log("==    接口数据:" + JSON.stringify(res.data));
        console.log('===========================================================================================')
        if (res.statusCode == 200) {
          resolve(res);
        } else if (res.statusCode == 401) {//授权失效
          reject("登录已过期");
          jumpToLogin();//跳转到登录页
        } else {
          //请求失败
          reject("请求失败:" + res.statusCode)
        }
      },
      fail: function (err) {
        //服务器连接异常
        console.log('==========================================================================================')
        console.log('==    接口地址:' + url)
        console.log('==    接口参数:' + JSON.stringify(data))
        console.log('==    请求类型:' + method)
        console.log("==    服务器连接异常")
        console.log('==========================================================================================')
        reject("服务器连接异常,请检查网络再试");
      },
      complete: function () {
        ui.hideLoading();
      }
    })
  });
}


//跳转到登录页  小程序每次启动登录  暂时没有登录页面
function jumpToLogin() {
    
}

module.exports = {
  request,
}

 ui.js

控制模态框

export const showToast = function(content,duration) {
  if(!duration) duration = 2000
  wx.showToast({
      title: content,
      icon: 'none',
      duration: duration,
  })
}

var isShowLoading = false
export const showLoading = function(title) {
  if(isShowLoading) return
  wx.showLoading({
      title: title?title:'',
      mask:true,
      success:()=>{
          isShowLoading = true
      }
  })
}

export const hideLoading = function() {
  if(!isShowLoading) return
  isShowLoading = false
  wx.hideLoading()
}

 app.js

// app.js

const httpUtils = require('./utils/httpUtils')
const ui = require('./utils/ui')
App({
  onLaunch() {
    //删除缓存  重新登录 获取会话
    wx.removeStorageSync('sessionid') 
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          //发起网络请求
          httpUtils.request({
            method: "GET", showLoading: true,url: `/wx/user/wxLogin`,message: "正在登录",
           data: {
              code: res.code
            }
          }).then(res => {
            // 保存set-cookie到缓存中
            if(res.header["Set-Cookie"]){
              wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
             }
            // 用户信息保存在全局变量
             this.globalData.userInfo = res.data.data
            ui.showToast(res.data.errorMsg)
          }).catch(err => {
            console.log('ERROR')
          });
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })
  },
  globalData: {
    userInfo: null,
  }
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kaiyu0426

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值