欢迎光临,了解微信小程序开发,就上易用通!

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

发布:2018-05-09 11:05浏览: 来源:网络 作者:cola

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

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

 

				
  1. Response Headers
  2. Content-Type:application/json;charset=UTF-8
  3. Date:Mon, 02 Apr 2018 16:02:42 GMT
  4. Set-Cookie:JSESSIONID=781C7F500DFA24D663BA243A4D9044BC;path=/yht;HttpOnly

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

 

				
  1. Request Headers
  2. Accept:*/*
  3. Accept-Encoding:gzip, deflate, br
  4. Accept-Language:zh-CN,zh;q=0.8
  5. Cache-Control:no-cache
  6. Connection:keep-alive
  7. Content-Length:564
  8. content-type:application/json
  9. Cookie:JSESSIONID=781C7F500DFA24D663BA243A4D9044BC;path=/yht;HttpOnly

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

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

简单的处理方法如下:

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

 

				
  1. wx.request({
  2. url: path,
  3. method:method,
  4. header: header,
  5. data:data,
  6. success:function(res){
  7. if(res && res.header && res.header['Set-Cookie']){
  8. wx.setStorageSync('cookieKey', res.header['Set-Cookie']);//保存Cookie到Storage
  9. }
  10. },
  11. fail:fail
  12. })
  13. wx.request再从Storage中取出Cookie,封装到header中
  14. let cookie = wx.getStorageSync('cookieKey');
  15. let path=conf.baseurl+url;
  16. let header = { };
  17. if(cookie){
  18. header.Cookie=cookie;
  19. }
  20.  
  21. wx.request({
  22. url: path,
  23. method:method,
  24. header: header,
  25. data:data,
  26. success:success,
  27. fail:fail
  28. })





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。