【问题标题】:Getting different sessionId from the same browser从同一个浏览器获取不同的 sessionId
【发布时间】:2019-12-20 18:42:51
【问题描述】:

我正在使用 node express-session 来尝试在 Angular 应用程序中进行持久会话。 每当我关闭浏览器窗口时,我都想清除会话。 问题是尝试清除SessionCookie时(在中间件函数的req参数中)通过浏览器请求发送的会话ID与使用getSession时发送的会话ID不同 - 相同的浏览器 -不同请求的不同会话 ID。 在 app.component 中触发它的客户端事件是:

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) 
{
  this.sessionSrv.clearSessionCookie().subscribe();
}

发送请求的客户端服务:

导出类 sessionService { apiPath : string = environment.apiUrl;

    constructor(private http: HttpClient) { }

    getSession() : Observable<any> \\this is used to get the session
    {
        var path = `${this.apiPath}/session`;
        const options = { withCredentials: true };
        return this.http.get<any>(path, options).pipe(   
            tap(res=>{ console.log('sessionCheck!'); }),
            catchError(error =>  throwError(error))
        );  
    }
    clearSessionCookie() : Observable<any> 
    {
        var path = `${this.apiPath}/session/clearSessionCookie`;
        const options = { withCredentials: true };
        //return this.http.get(path);
        return this.http.post(path, options);
    }
}

负责将请求路由到端点的节点服务器端代码:

session.js:

const express = require('express');
const router = express.Router();
var sessionManagement = require('../../middleware/sessionManagement');

router.use("/clearSessionCookie", (req, res, next) => 
{
    sessionManagement.clearSessionCookie(req, res, next);
});

router.use("/", (req, res, next) => 
{ 
    sessionManagement.getUserSession(req, res, next);
});

module.exports = router;

节点服务器端相关功能: sessionManagement.js

module.exports = 
{
    getUserSession : function (req, res)
    {
        if (req.session && req.session.user)
        {
            res.status(200).json(req.session.user);
        }
        else{
            res.sendStatus(403);
        }
    },


    clearSessionCookie : function(req, res, next)
    {
        res.clearCookie('user_sid');  
        req.session = null;
        //next();
        //res.status(401);
        res.end();
    }
}

【问题讨论】:

    标签: node.js angular express angular-routing express-session


    【解决方案1】:

    我找到了这种现象的根本原因 - 问题是 clearSessionCookie 函数被发布到服务器,因此 - 没有 cookie 随请求传输,所以创建了 express-session新会话,因为它无法识别发送的会话(无 cookie)。 就我而言,解决方案很简单 - 使用“get”(withCredentials = “true”,这很重要)而不是帖子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2012-05-30
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2020-01-17
      • 2011-12-29
      • 1970-01-01
      相关资源
      最近更新 更多