解决微信自动清除缓存,每天都需要重新登录
问题场景:新版微信会自动清空cookie,导致每天都要重新登录
解决思路:后端是通过session来获取用户是否登录,而session信息会存在客户端的cookie里面,然后每次请求接口的时候。又会自动带上cookie上面的信息,传给后端。所以我们可以在登录的时候让后端把登录信息传过来,然后存在localstorage里面,在首页需要登录的页面里面获取localstorage里面的值,设置在cookie上,这样在每次进行ajax请求的时候,浏览器会自带将存在cookie上面的用户信息传过去,服务器会根据cookie上面的信息去数据库读取sessionid做判断!!!!
login页面
flag = false; $.ajax({ url:'ajaxLogin', type:'post', data:{"nc_token":nc_token,"csessionid":csessionid,"scene":scene,"sig":sig,tel:tel,verifyCode:verifyCode,redirect_url:redirect_url,remeber:1, from : from}, success: function(res){ //console.log(res); if(res.status == 1000){ var tipMsg = res.data ? res.data : '登录成功~'; //$.alert('tipMsg'); window.localStorage.setItem('username',tel); $('#getVerifyCode').removeClass('btn-blue').addClass('btn-disabled'); flag = true; setTimeout(function(){ window.location.href = res.data },500); //pobp838totku433ts210d7b2s0 var PHPSESSID_cookie = getCookie("PHPSESSID"); var m_enstr = getCookie('m_enstr'); if(PHPSESSID_cookie){ window.localStorage.setItem("PHPSESSID",PHPSESSID_cookie); window.localStorage.setItem("act_m_enstr",m_enstr); } window.localStorage.setItem("act_login",1); var expires = new Date().getTime() + 14*24*3600*1000; window.localStorage.setItem("expires",expires); }else{ $.alert(res.data); flag = true; } }, error: function(){ $.alert('出错啦!'); flag = true; } })
index
//判断是否登录 var is_login = "{$is_login}"; if (!is_login) { var act_login = window.localStorage.getItem("act_login"); var expires = parseInt(window.localStorage.getItem("expires")); var PHPSESSID = window.localStorage.getItem("PHPSESSID"); var act_m_enstr = window.localStorage.getItem('act_m_enstr'); var nowtime = new Date().getTime(); var PHPSESSID_oldcookie = getCookie("PHPSESSID"); if (PHPSESSID_oldcookie != PHPSESSID) { if (act_login == "1" && nowtime < expires) { setCookie("PHPSESSID", PHPSESSID, 14); setCookie("m_enstr", act_m_enstr, 14); window.location.reload(); } } }