nodejs使用session和cookie

session:

1.安装模块

npm install express-session

2.引入session注册到路由

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

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

3.使用session

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

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

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

session存在于会话之中,只要连接断开session就会消失,所以使用session需要注意

 

cookie:

1.安装模块

npm install cookie-parse

2.引入session注册到路由

let express = require('express');
let cookie = require('cookie-parser');
let router = express.Router();
let app = express()
app.use(cookieParser());

3.使用cookie

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

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

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

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

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

 

 

 

你可能感兴趣的:(Nodejs,node,nodejs)