使用不使用 express.js 的核心 node.js 进行会话管理 [英] session management using core node.js without express.js
问题描述
如何在核心 node.js/非 express.js 项目中处理/创建用于服务器端会话管理的中间件.我可以为基于 express 的项目找到模块,但不能为核心 node.js 找到模块.请为我推荐任何非 express.js 项目的模块或中间件.
How to handle/create middleware for server side session management in a core node.js /non express.js project. I can find modules for express based project but not for core node.js. Please suggest me any modules or middleware for non express.js project.
推荐答案
会话管理可以通过数据库(MySQL、MongoDB、Redis等)或一些本地缓存来实现.
会话背后的主要逻辑 - 是带有数据的对象.
因此,您可以在第一次交互时为用户提供一些随机 ID,例如 uuid
.
并将其保存到某个模块中,如下所示:
Session management can be implemented via database (MySQL, MongoDB, Redis etc.) or some local cache.
The main logic behind sessions - is object with data.
So you can provide user on first interaction with some random id, like uuid
.
And save it to some module, which looks like this:
class OwnSession(){
constructor(){
this.sessions = {};
}
getUser(sessionId){
return this.sessions[sessionId];
}
setUser(sessionId, userData){
if(this.sessions[sessionId]){
Object.assign(this.sessions[sessionId], userData);
return;
}
this.sessions[sessionId] = userData;
}
}
// We export here new OwnSession() to keep singleton across your project.
module.exports = new OwnSession();
然后,在任何模块中,您都需要 OwnSession
并调用该方法.
And then, in any module you require OwnSession
and call the method.
这篇关于使用不使用 express.js 的核心 node.js 进行会话管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!