美文网首页
Node.js -- cookie and session

Node.js -- cookie and session

作者: 苦茶_12138 | 来源:发表于2018-05-01 13:04 被阅读0次

    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("<h1>设置cookie页面</h1>")

                    })

            4,获取cookie

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

                        var username = req.cookies.username;

                        res.send("<h1>用户名是${username}</h1>");

                })

                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("<h1>设置session界面</h1>");

            })

    4,获取session

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

                    var username = req.session.username;

                    res.send("<h1>用户名是${username}</h1>")

            })

        app.listen(8686);

    相关文章

      网友评论

          本文标题:Node.js -- cookie and session

          本文链接:https://www.haomeiwen.com/subject/oitulftx.html