在快递中保持可靠的会话 [英] Maintaining a reliable session in express

查看:59
本文介绍了在快递中保持可靠的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Nodejs并表示要创建一个Web应用程序.但是我发现维持会议有些困难.我可以使用req.session.userid = userid,但是它不是那么可靠.如果服务器关闭一段时间后必须重新启动,则会话将丢失.是否有任何方法可以更有效地存储会话?

I am using Nodejs and express to create a web app. But i am finding some difficulty in maintaining session. i can use req.session.userid = userid , but it is not so reliable. if the server goes down for some time and it has to reboot, the session will be lost.. Is there any way to store the session more effectively?

推荐答案

我更喜欢使用名为"connect-mongodb-session"的npm模块.它使用mongodb存储所有会话.转到您的项目目录,然后使用

I prefer using the npm module called "connect-mongodb-session". It uses mongodb to store all the sessions. Go to your project directory and install "connect-mongodb-session" using

sudo npm install connect-mongodb-session

sudo npm install connect-mongodb-session

并将其作为依赖项添加到package.json中.这就是您可以使用它的方式.

And add this to your package.json as dependencies. and this is how you can use it..

示例代码...

var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);

var app = express();
var store = new MongoDBStore({ 
    uri: 'mongodb://localhost:27017/connect_mongodb_session_test',
    collection: 'mySessions'
});

// Catch errors 
store.on('error', function(error) {
    assert.ifError(error);
    assert.ok(false);
});

app.use(require('express-session')({
    secret: 'This is a secret',
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week 
    },
    store: store
}));

server = app.listen(3000);

您很高兴..随时使用req.session,您的会话将存储在mongodb中.

And you are good to go.. use req.session when ever you want, and your sesion will be stored save in mongodb.

例如.

app.post("/login",function(req,res){
    //validate login
    req.session.userid = userid;
})

即使服务器必须重新启动,您的会话也不会丢失.

even if the server has to reboot, your session will not be lost.

这篇关于在快递中保持可靠的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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