Nodejs中的会话管理 [英] Session management in Nodejs
问题描述
我是NodeJS的初学者。刚刚开始了一个我需要会话管理概念的简单项目。那么如何在NodeJS应用程序中管理会话。
I am beginner of NodeJS.And just started a simple project where I need a session management concept. So How to manage the session in NodeJS application.
在我的项目中有两个文件: - app.js和routes.js。
In my project there is two file:- app.js and routes.js.
那么我们在哪里添加会话以及如何添加??
So where we add the session and how to add ??
app.js文件: -
app.js file :-
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");
});
和routes.js文件: -
and routes.js file :-
module.exports = function(express, app){
var router = express.Router();
router.get('/', function(req , res , next){
res.render('index',{title: 'Welcome'});
});
}
推荐答案
会话管理我们需要一个中间件'cookie-parser'。以前它是express的一部分,但是在express 4.0及之后它是一个单独的模块。
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解析器:
So to access the cookie parser we need to install in our project as :
npm install cookie-parser --save
npm install cookie-parser --save
然后将其添加到app.js文件中:
Then add this into your app.js file as :
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 --save
然后启用会话。我们在app.js文件中添加以下代码。
Then to enable the session. we add below code in app.js file.
app.use(session({secret:config.sessionSecret, saveUninitialized : true, resave : true}));
然后来到routes.js文件: -
Then come to the routes.js file :-
我们假设有一个会话变量favColor。现在使用session设置颜色并进入另一页。代码如下所示: -
Let us suppose there is a session variable favColor. Now using session set the color and get in the other page. 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
这篇关于Nodejs中的会话管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!