Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

express中 用ajax给session赋值,页面跳转后session丢失

有没有人遇到了相同的问题


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

不知道你能不能打开这个链接:
https://baudehlo.com/2016/02/...

原文节选:"Express saves the session by hijacking res.end(). It turns out that when you do a res.redirect(), on Windows it will likely get the headers in a single packet, and the body in another, but perform the redirect before even seeing the body (because it’s empty and irrelevant). But res.end() isn’t called until the HTTP request is completed. This means the Windows boxes can get the redirect, request the redirected URL, and get access to an unsaved session before res.end() has time to completely save the session. The fix? Now in our code we hijack res.redirect() to perform req.session.save() before performing the actual redirect."

他说的意思好象是: 当你设置session时,session的保存动作是随着res.end的调用才触发的, 当你在windows里面跑时, 服务器响应是先发一个响应头的数据包给浏览器,然后再发响应体的包,之后res.end才会被调用(调用后,设置的session此时也才会被保存), 但是, 就是因为这个响应头的数据包就足够可以触发浏览器的重定向操作(此时响应体可能还在发送,res.end还没被调用,session也没有被保存)从而导致重定向的请求获得的是服务器未保存的那个session。

他给了一坨代码(我也看不懂):

var redirect = res.redirect;
 res.redirect = function (path) {
 res.redirect = redirect;

 if (req.session) {
 req.session.save(function (err) {
 if (err) console.error(err);
 _finish();
 });
 }
 else {
 _finish();
 }

 function _finish () {
 if (/&utm_/.test(path)) {
 return res.redirect(path);
 }
 if (req.query.utm_campaign && req.query.utm_medium && req.query.utm_source) {
 var extras = qs.stringify({
 utm_campaign: req.query.utm_campaign,
 utm_medium: req.query.utm_medium,
 utm_source: req.query.utm_source,
 });
 if (/?./.test(path)) {
 path = path + '&' + extras;
 }
 else {
 path = path + '?' + extras;
 }
 }
 return res.redirect(path); 
 }
 }

我赶脚主题思想就是要强行手动在res.redirect启动之前保存session(怎么保存的,请想办法看明白代码,估计大概就是异步保存session然后再调用redirect,奥秘核心应该在req.session.save(function (err) {})这个地方附近, 其他那些估计不是太重要,我也不懂哦)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...