137-3385-8848(同微信)

小程序保存服务端sessionid的方法

2022-04-21 管理员

普通的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的调试,小程序扫码接口微信支付普通的转发
下一篇:微信小程序工具程序调试,模拟器、调试工具和小程序操作区
相关资讯 Releva ntnews
解决方案 Solutions
相关热点 Hot spot
郑州做排名中正确使用关键词优化的方法
  1. 我们的优势
  2. 我们的实力
  3. 选择我们的理由
咨询电话(微信同号)

137-3385-8848(同微信)

豫ICP备16014343号-1

Copyright © 2017-2022 版权所有 酷微科技 Rights Reserved

电话咨询 在线咨询 服务项目 SEO优化