普通的Web開發(fā),都是把sessionid保存在cookie中傳遞的。
不管是java還是php,服務(wù)端的會在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就能使瀏覽器端和服務(wù)端保持會話,使瀏覽器端保持登錄狀態(tài)
但是,微信小程序不能保存Cookie,導(dǎo)致每次wx.request到服務(wù)端都會創(chuàng)建一個新的會話,小程序端就不能保持登錄狀態(tài)了
簡單的處理方法如下:
1、把服務(wù)端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
-
})
|