小程序保存服務端sessionid的方法
2020-09-27
導讀:普通的Web開發,都是把sessionid保存在cookie中傳遞的。那么小程序保存服務端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到服務端都會創建一個新的會話,小程序端就不能保持登錄狀態了
簡單的處理方法如下:
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
- })
第二部分:如何開通一個小商店
您可能感興趣: 小程序開發
上一篇:微信小程序遮罩功能開發流程
下一篇:微信小程序點擊實現樣式切換功能