简体   繁体   English

Nodejs中的会话管理

[英]Session management in Nodejs

I am beginner of NodeJS.And just started a simple project where I need a session management concept. 我是NodeJS的初学者,刚刚开始一个需要会话管理概念的简单项目。 So How to manage the session in NodeJS application. 那么如何在NodeJS应用程序中管理会话。

In my project there is two file:- app.js and routes.js. 在我的项目中,有两个文件:-app.js和routes.js。

So where we add the session and how to add ?? 那么我们在哪里添加会话以及如何添加??

app.js file :- app.js文件:-

 var express = require('express'), app = express(), path = require('path'); app.set('views', path.join(__dirname , 'views')); app.engine('html', require('hogan-express')); app.set('view engine', 'html'); app.use(express.static(path.join(__dirname,'public'))); require('./routes/routes.js')(express,app); app.listen (3000 , function(){ console.log("working on the Port 3000"); }); 

and routes.js file :- 和routes.js文件:-

 module.exports = function(express, app){ var router = express.Router(); router.get('/', function(req , res , next){ res.render('index',{title: 'Welcome'}); }); } 

For the session management we need a middleware 'cookie-parser'.Previously it is the part of express but after express 4.0 and later it is a separate module. 对于会话管理,我们需要一个中间件'cookie-parser',以前它是express的一部分,但在express 4.0之后,后来是一个单独的模块。

So to access the cookie parser we need to install in our project as : 因此,要访问cookie解析器,我们需要在项目中安装以下代码:

npm install cookie-parser --save npm install cookie-parser-保存

Then add this into your app.js file as : 然后将其添加到您的app.js文件中,如下所示:

 var cookieParser = require('cookie-parser'); app.use(cookieParser()); 

Then we reqired session module. 然后我们需要会话模块。 So first of all install the session module by : 因此,首先通过以下方式安装会话模块:

npm install express-session --save npm install express-session-保存

Then to enable the session. 然后启用会话。 we add below code in app.js file. 我们在app.js文件中添加以下代码。

 app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true})); 

Then come to the routes.js file :- 然后进入routes.js文件:

Let us suppose there is a session variable favColor. 让我们假设有一个会话变量favColor。 Now using session set the color and get in the other page. 现在使用session设置颜色并进入其他页面。 the code is look like :- 代码看起来像:-

 router.get('/setColor', function(req , res , next){ req.session.favColor = 'Red'; res.send('Setting favourite color ...!'); }); router.get('/getColor', function(req , res , next){ res.send('Favourite Color : ' + (req.session.favColor == undefined?"NOT FOUND":req.session.favColor)); }); 

This is all about the session management.We can also learn more about the session :- This Reference 这全都与会话管理有关。我们还可以了解有关会话的更多信息:- 本参考

我不建议您尝试建立自己的会话并改用https://github.com/expressjs/session ,它可以很好地表达。

An update on 2019, using express-session 1.15.6 (From 1.5 there's no need to use cookie-parser , session can read and write the cookie directly.) 使用express-session 1.15.6的2019年更新(从1.5开始,无需使用cookie-parser ,session可以直接读写cookie。)

In app.js: 在app.js中:

const app = express()
const session = require('express-session');
const options = {
  name: 'foo', // Default is connect.sid
  store: this.store, // Default is memoryStore, which is for dev only. Setup redis or memcached for prod
  secret: 'bar', // Required, used to sign session id cookie
  saveUninitialized: true, // Forces a session that is "uninitialized" to be saved to the store
  resave: false, //Forces the session to be saved back to the session store
  rolling: true //Force a session identifier cookie to be set on every response
};
// Session method will return a middleware function.
const middleware = session(options);
// Now we can make use of session in all the requests
app.use(middleware)

In routes.js or in any handler file created for specific route: 在routes.js或为特定路由创建的任何处理程序文件中:

handler1(req, res, next) {
  req.session.someField = 'foo';
  // Use save method to update the store immediately, if there's other AJAX call pending. 
  req.session.save();
}

handler2(req, res, next) {
  console.log(req.session.someField); 
}

handler3(req, res, next) {
  // we use delete operator here.
  delete req.session.someField; 
}

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

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