微信小程序使用cookie保持session

 3442

微信小程序不能保存Cookie,导致每次wx.request到服务端都会创建一个新的会话(传过去的sessionid会变化),小程序端就不能保持登录状态了。

一个比较简单的办法就是把服务端response的Set-Cookie中的值保存到Storage中。

登录成功后,添加Cookie:

  1. wx.setStorageSync("cookieKey", res.header["Set-Cookie"]);

然后调用接口时,在header中加入:

  1. 'Cookie': wx.getStorageSync('cookieKey')

接口调用由之前的:

  1. wx.request({
  2.     url: 'test.php',
  3.     data: {
  4.         x: '',
  5.         y: ''
  6.     },
  7.     header: {
  8.         'content-type': 'application/json' 
  9.     },
  10.     success (res) {
  11.         console.log(res.data)
  12.     }
  13. })

变为:

  1. wx.request({
  2.     url: 'test.php', 
  3.     data: {
  4.         x: '',
  5.         y: ''
  6.     },
  7.     header: {
  8.         'content-type': 'application/json' ,
  9.         'Cookie': wx.getStorageSync('cookieKey')
  10.     },
  11.     success (res) {
  12.         console.log(res.data)
  13.     }
  14. })



本文网址:https://www.zztuku.com/index.php/detail-8836.html
站长图库 - 微信小程序使用cookie保持session
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐