场景一:通过接口获取短信验证码,提交表单时进行检查验证码是否正确,这时候发现session失效。
分析:上面发生了两次请求,可以发现每一次,响应头都有Set-Cookie,这也就说明了每一次都是创建一个新的会话,所以导致了session丢失的问题。
解决方案:只要保证这两次请求是同一次会话即可
如何区分请求是不是同一次会话,检查Request Headers 和 Response Headers,如果Request Header中的cookie为空,说明是已继承了上一次的请求的同一个会话;如果Response Headers中有Set-Cookie那么说明本次会话是一次新的会话请求。
Response Headers
HTTP/1.1 200 OK
Server: nginx/1.15.11
Date: Tue, 14 Dec 2021 06:44:36 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.2.9
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
for-weapp-devtools: {"Server":["nginx/1.15.11"],"Date":["Tue, 14 Dec 2021 06:44:36 GMT"],"Content-Type":["text/html; charset=utf-8"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"X-Powered-By":["PHP/7.2.9"],"Expires":["Thu, 19 Nov 1981 08:52:00 GMT"],"Cache-Control":["no-store, no-cache, must-revalidate"],"Pragma":["no-cache"]}
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate
aud: https://www.mainweb.cc
Connection: keep-alive
content-type: application/json
cookie:
Host: 10.0.0.33
Referer: https://servicewechat.com/wxc48fd9f1e0de18a7/devtools/page-frame.html
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 wechatdevtools/1.05.2111051 MicroMessenger/8.0.5 Language/zh_CN webview/
小程序解决方案:
wx.request(
{
url,
method,
data,
header: {cookie:wx.getStorageSync('session_id')},
success(res) {
if(res.header['Set-Cookie']){
wx.setStorageSync('session_id', res.header['Set-Cookie']);
}
},
fail(err) {}
})