nodejs操作session和cookie

不該相遇在秋天發表於2017-11-30

 

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: '首頁'});
});

 

相關文章