普通的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到服务端都会创建一个新的会话,小程序端就不能保持登录状态了
简单的处理方法如下:
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
-
})
-
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
-
})
|