nodejs操作session和cookie

 

session:

安装模块

cnpm install express-session

 

引入session注册到路由

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

router.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: {maxAge: 60000}}));

 

操作session

router.get('/', function (req, res, next) {
    
    //设置session
    req.session.username = 'zhangsan';

    //获取session
    console.log(req.session);
    console.log(req.session.myname);

    res.render('/index', {title: '首页'});
});

session存在于会话之中,连接一断,session消失,因此在开发阶段使用session请做好抓狂的准备。

 

 

cookie:

安装模块

cnpm install cookie-parser

 

引入cookie

var express = require('express');
var cookie = require('cookie-parser');
var router = express.Router();

 

操作cookie

router.get('/', function (req, res, next) {

    //设置cookie
    res.cookie('username','zhangsan');
    res.cookie('username','zhangsan',{maxAge:10000}); //有效期以毫秒为单位

    //获取cookie
    console.log(req.cookies);
    console.log(req.cookies.username);

    //删除cookie
    res.clearCookie('username');

    res.render('/index', {title: '首页'});
});

 

posted @ 2017-11-30 17:53  不该相遇在秋天  阅读(9510)  评论(0编辑  收藏  举报