普通的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. wx.request({
  21. url: path,
  22. method:method,
  23. header: header,
  24. data:data,
  25. success:success,
  26. fail:fail
  27. })
http://www.wxapp-union.com/portal.php?mod=view&aid=3886


本文转载:CSDN博客