Node.js -- cookie and session

1.    cookie  

        1,引入模块

                var express = require ("express");

                var app = express();

                var  cookieParser =  require ("cookie-parser");

        2,中间件引用

                app.use(cookieParser());

        3,设置cookie

                //设置过期时间两种方式

               // 1,maxAge     maxAge:1000*60*60(代表1小时之后过期)

                2,expires   当前时间+过期时间GMT

                    var nowtime = new Date();

                    nowtime.setDate(nowtime.getDate()+7);

                app.get("/setcookie",function(req,res){

                        res.cookie("username","李四",{

                                expires:nowtime

                        })

                    res.send("

设置cookie页面

")

                })

        4,获取cookie

            app.get("/getcookie",function(res,req){

                    var username = req.cookies.username;

                    res.send("

用户名是${username}

");

            })

            app.listen(8989);

2.   session

        1,引入模块

                var express = require ("express");

                var session = require("express-session);

                var app = express();

        2,中间件引用,配置

                app.use(session({

                        secret : "mysecret",

                        resave:false,

                        saveUninitialized:false

                }))

    3,设置session

        app.get("/setsession",(req.res)=>{

                req.session.username="erha";

                res.send("

设置session界面

");

        })

4,获取session

        app.get("/getsession",(req,res)=>{

                var username = req.session.username;

                res.send("

用户名是${username}

")

        })

    app.listen(8686);

你可能感兴趣的:(Node.js -- cookie and session)