Home > Article > WeChat Applet > The solution to the problem that session retention of WeChat applet will fail next time
All HTTP requests of the applet use the wx.request({}) method, but this method will generate a new session every time, so it is not suitable for specific usage scenarios (security verification, session saving, CSRF protection), etc. There will be some troubles. For example, in a CSRF-protected application, even if the CSRF was obtained last time, it will be invalid in the next request.
The csrf has been obtained as an example, simple and crude, when the application starts () You can obtain the cookie information for the first request during onLaunch and save it locally. You can force the cookie information to be added to the request header every time in the future.
The code is as follows:
//app.jsApp({ onLaunch:function(){ this.initSession(); }, initSession:function(){ var that = this; // step one:get cookie wx.request({ url:'https://my.domain.com/open-api/cookie', header:{'Content-Type':'application/x-www-form-urlencoded'}, method:'GET', success:function(res){ for(let cookie of res.data){ //这里我仅保存了sessionid,根据需要,也可以保存cookie的其它信息。 if(cookie.name === 'JSESSIONID') { that.globalData.sessionId=cookie.value; wx.request({ url:'https://my.domain.com/open-api/csrf', header:{'Content-Type':'application/x-www-form-urlencoded','Cookie':'JSESSIONID='+that.globalData.sessionId}, method:'GET', success:function(res){ that.globalData.csrf=res.data; } }) break; } } } }) } })
After that, every time you request another api interface, you can add csrf and csrf to the request header. sessionId to maintain the same session.
The code is as follows:
doSth:function(){ var that = this; wx.request({ url:'my.domain.com/api/some-thing', //这里的CSRF的key(CSRF-TOKEN)具体写什么,根据各位自己的程序设置来写 header:{'Content-Type':'application/x-www-form-urlencoded','Cookie':'JSESSIONID='+that.globalData.sessionId,'CSRF-TOKEN':that.globalData.csrf}, method:'POST', data:paramdata, success:function(res){ doSomething(res.data); } }) }
The above is the detailed content of The solution to the problem that session retention of WeChat applet will fail next time. For more information, please follow other related articles on the PHP Chinese website!