【发布时间】: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