微信小程序开发之保存服务端sessionid的方法总结

普通的Web开发,都是把sessionid保存在cookie中传递的。

不管是java还是php,服务端的会在response的header中加上Set-Cookie

Response HeadersContent-Type:application/json;charset=UTF-8Date:Mon, 02 Apr 2018 16:02:42 GMTSet-Cookie:JSESSIONID=781C7F500DFA24D663BA243A4D9044BC;path=/yht;HttpOnly

浏览器的请求也会在header中加上

Request HeadersAccept:*/*Accept-Encoding:gzip, deflate, brAccept-Language:zh-CN,zh;q=0.8Cache-Control:no-cacheConnection:keep-aliveContent-Length:564content-type:application/jsonCookie:JSESSIONID=781C7F500DFA24D663BA243A4D9044BC;path=/yht;HttpOnly

通过这个sessionid就能使浏览器端和服务端保持会话,使浏览器端保持登录状态

但是,微信小程序不能保存Cookie,导致每次wx.request到服务端都会创建一个新的会话,小程序端就不能保持登录状态了

简单的处理方法如下:

1、把服务端response的Set-Cookie中的值保存到Storage中

wx.request({    url: path,    method:method,    header: header,    data:data,    success:function(res){        if(res && res.header && res.header['Set-Cookie']){            wx.setStorageSync('cookieKey', res.header['Set-Cookie']);//保存Cookie到Storage          }},    fail:fail  })wx.request再从Storage中取出Cookie,封装到header中  let cookie = wx.getStorageSync('cookieKey');  let path=conf.baseurl+url;  let header = { };  if(cookie){    header.Cookie=cookie;  }  wx.request({    url: path,    method:method,    header: header,    data:data,    success:success,    fail:fail  })





来源:春哥技术博客,欢迎分享,转载请注明出处。(欢迎加春哥团队客服微信号:taike668)

本文地址:https://www.cgtblog.com/wx/3156.html
上一篇:微信小程序开发之遮罩功能实现教程案      下一篇:微信小程序&PHP 获取小程序码 并改变