在快递中保持可靠的会话

编程入门 行业动态 更新时间:2024-10-24 02:01:44
本文介绍了在快递中保持可靠的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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.

更多推荐

在快递中保持可靠的会话

本文发布于:2023-07-15 10:24:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快递   可靠

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!