简体   繁体   English

Node.js处理与数据库的会话

[英]Node.js Handle session with database

Basically I have a Node.js web application which uses the express-session module to handle sessions. 基本上,我有一个Node.js Web应用程序,该应用程序使用express-session模块来处理会话。

It works perfectly but with 1 expectation which ruins this option for me. 它完美地工作,但是有1个期望,这对我来说是个坏选择。 If the Server crashes or I deploy a new release, the sessions get wiped out complety and thats unacceptable for me. 如果服务器崩溃或我部署了新版本,则会话将完全消失,这对我来说是不可接受的。 Also its bad that I cant share the session between my main and my backup server. 同样糟糕的是,我无法在主服务器和备份服务器之间共享会话。

So my goal is to handle the session via a external cloud database, just think of it as a "casual mysql database". 因此,我的目标是通过外部云数据库处理会话,只需将其视为“休闲mysql数据库”即可。

But here is the point were I just get confused on how to do that. 但这就是我对如何做到这一点感到困惑的意思。 I can assign unique ids to the sessions and depending on those load the resources from the database, but how can I re-recognize the users if these sessions get wiped away? 我可以为会话分配唯一​​的ID,并根据这些ID从数据库中加载资源,但是如果这些会话消失了,如何重新识别用户?

I am lacking alot of knowledge about sessions, but since this is quite a critical topic for me I post a question here. 我缺乏有关会议的知识,但是由于这对我来说是非常关键的主题,因此我在此处提出了一个问题。

You can use any of those stores (or write your own) : 您可以使用任何这些商店(或编写您自己的商店):

https://www.npmjs.com/package/express-session#compatible-session-stores https://www.npmjs.com/package/express-session#compatible-session-stores

I'm using the connect mongo to store sessions in my mongo DB, code looks like this (app.js) : 我正在使用connect mongo将会话存储在mongo DB中,代码看起来像这样(app.js):

import session from 'express-session';
const MongoStore = require('connect-mongo')(session);
...
...
    api.use(session({
        secret: global.config.secrets.session,
        saveUninitialized: false, // don't create session until something stored
        resave: false, //don't save session if unmodified
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            touchAfter: 24 * 3600 // time period in seconds
        })
    }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM