码迷,mamicode.com
首页 > Web开发 > 详细

nodejs操作session和cookie

时间:2017-11-30 19:20:50      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:npm   parser   clear   zha   san   设置   color   key   board   

 

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: ‘首页‘});
});

 

nodejs操作session和cookie

标签:npm   parser   clear   zha   san   设置   color   key   board   

原文地址:http://www.cnblogs.com/fengyumeng/p/7930265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!