小程序模板网

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

发布时间:2018-05-09 11:05 所属栏目:小程序开发教程

普通的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. })


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/24355.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询