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

查看:306
本文介绍了express中 用ajax给session赋值,页面跳转后session丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

不知道你能不能打开这个链接:
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) {})这个地方附近, 其他那些估计不是太重要,我也不懂哦)

这篇关于express中 用ajax给session赋值,页面跳转后session丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆