需要下载安装
npm install express-session --save
var session = require('express-session');
express-session模块的详细介绍请查看《node.js中express-session中文配置项详解》
此模块需要借助cookie-parser模块来实现,即使关闭了页面依然还能记录着登录的状态效果,如果是使用express那么已经内置安装好了
使用:
var cookieParser = require('cookie-parser');
var session = require('express-session'); //加载
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ //配置信息,并调用
secret: '12345',
name: 'testapp',
cookie: {maxAge: 3020000 }
//resave: false,
//saveUninitialized: true
}));
单独设置过期时间:
req.session.cookie.maxAge = 1000 //1秒后过期
设置值:
req.session.xxx='123';
取值:
req.session.xxx
删除:
req.session.destroy();
—————————————————————————
session配合mongodb
环境:
“connect-mongo”: “^1.3.2”,
“express”: “~4.13.4”,
“express-session”: “1.9.1”,
1,安装express-session和connect-mongo
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
2,编辑app.js添加如下代码
app.use(express.static(path.join(__dirname, 'public')));
//添加以下代码
app.use(session({
secret: 'myblog',
key: 'blog',//cookie name
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
store: new MongoStore({
url: 'mongodb://blog:123@localhost:27017/blog'
}),
resave:false,//添加这行
saveUninitialized: true//添加这行
//以上两行解决 express-session deprecated undefined resave option; provide resave option app.js 报错问题
}));
connect-mongo参数:https://github.com/jdesboeufs/connect-mongo
3,创建数据库blog,用来存储session数据
use admin
db.createRole({role:'sysadmin',roles:[],privileges:[{resource:{anyResource:true},actions:['anyAction']}]})
如果admin已经按照上面方法创建了,就略过,接下来创建blog数据库
use blog
db.createUser({user:'blog',pwd:'123',roles:[{role:'sysadmin',db:'admin'}]})
连接数据库blog的帐号是blog 密码是123