美文网首页
微信小程序session

微信小程序session

作者: 贝灬小晖 | 来源:发表于2018-12-17 16:08 被阅读20次

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

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

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

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

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

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

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

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

一个比较简单的办法就是在小程序端把cookie保存到storage里,后续请求的时候再读storage,把cookie添加到请求头里,这样做的好处就是,服务端不用做任何改动
具体操作如下:

  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
  })

  1. 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
  })

文章正解。但我在这里还遇到了另外一个问题,当服务器响应多个Set-Cookie时,小程序所取到的Set-Cookie会把它们用逗号分隔,从而产生的错误的Cookie。而真正需要的是用分号分隔。例如:
服务器响应:
Set-Cookie:session_name=184299abe5d9ac09559df76bff200a7985e55f86; expires=Tue, 23-Oct-2018 09:15:38 GMT; Max-Age=7200; path=/; HttpOnly
Set-Cookie:shop_rootpath=app%2Fsmallapp
小程序通过res.header['Set-Cookie']取到的Set-Cookie值却是:
"shop_rootpath=app%2Fsmallapp,session_name=184299abe5d9ac09559df76bff200a7985e55f86; expires=Tue, 23-Oct-2018 09:15:38 GMT; Max-Age=7200; path=/; HttpOnly"
而真正正确的值应该是smallapp与session_name之间用分号隔开而不是逗号:
"shop_rootpath=app%2Fsmallapp;session_name=184299abe5d9ac09559df76bff200a7985e55f86; expires=Tue, 23-Oct-2018 09:15:38 GMT; Max-Age=7200; path=/; HttpOnly"
这个问题怎么破?

转自:
https://www.jianshu.com/p/5c928e0df024

相关文章

网友评论

      本文标题:微信小程序session

      本文链接:https://www.haomeiwen.com/subject/gqrckqtx.html