node express-session配置

app.js

var seassion = require('express-session');

app.use(
    seassion({
        // cookies字段名
        name: 'session_id',
        // sessionID签名
        secret: 'ZjhETwRQs8ZNZ5',
        // 是否每次都重新保存会话,建议false
        resave: false,
        // 是否自动保存未初始化的会话,建议false
        saveUninitialized: false,
        cookie: {
            // domain:'.localhost'
            // 有效期
            maxAge: 1000 * 60 * 60 * 24 * 30,
            secure: false
        }
    })
);

 

route.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res) {
    if (req.session.user) {
        res.redirect('home');
    } else {
        res.render('index');
    }
});

router.post('/login', function (req, res) {
    let user = {
        name: '222',
        passwd: '333'
    };
    if (req.body.user === user.name && req.body.passwd === user.passwd) {
        req.session.user = user;
        res.send({ status: 1, msg: 'success' });
    } else {
        res.send({ status: 0, msg: 'error' });
    }
});

router.get('/logout', function (req, res) {
    if (req.session.user) {
        req.session.destroy(function (err) {
            if (err) {
                res.send({ status: 0, msg: 'failed' });
                return;
            }
            // 删除cookie:res.clearCookie('属性名')
            res.clearCookie('session_id');
            res.send({ status: 1, msg: 'success' });
        });
    } else {
        res.redirect(302, '/');
    }
});

router.get('/home', function (req, res) {
    if (req.session.user) {
        console.log(req.session);

        res.render('home');
    } else {
        res.redirect(302, '/');
    }
});

module.exports = router;

 

你可能感兴趣的:(node express-session配置)