进行session存储时需引用中间件,app.js
var express=require('express');
var app=express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
 
app.use(cookieParser('sessiontest'));
app.use(session({
    secret: 'sessiontest',//与cookieParser中的一致
    resave: false,
    saveUninitialized:true
}));
具体配置项可以查看相应文档进行了解
 
/*设置完毕后进行路由设置,注意先后顺序,路由设置应放在cookie及session设置之后*/
app.use('/public',express.static(staticDir));
app.use('/page',require('./routes/web-page'));
 
路由控制文件 web-page.js
var express=require('express');
var router=express.Router();
var userModel=require('../modules/user').user;  //user表
var deviceModel=require('../modules/device').device;
var bodyParser = require('body-parser');
 
router.post('/login',function (req,res) {
    var user=req.body.user;
    var code=req.body.password;
    userModel.authenticate(user,code,function (err,data) {
        if(err) res.send({status:-1,msg:err.name});
        if(data.status==0){
            var userInfo={name:data.msg.name,role:data.msg.role,limit:data.msg.limit};
            console.log(userInfo);
            req.session.user=userInfo;       //设置session
            res.send({status:0,msg:'成功'});
        }
        else {
            res.send(data);
        }
    });
});
 
router.get('/header',function (req, res) {
    if(req.session.user){
        res.render('header',{userName:req.session.user.name,roleName:req.session.user.role});     //将session中的值通过模板渲染,然后在页面中显示
    }
    else {
        res.render('header',{userName:'test',roleName:'test'});
    }
});