因为http会话的无状态性,为了标记用户的登录状态,便出现了cookie。cookie分为很多种,有普通cookie、签名cookie、json cookie等,这里主要记录下在express应用中如何配置使用cookie及session。
cookie
首先是app.js中的配置:
... var cookieParser = require(‘cookie-parser‘); var bodyParser = require(‘body-parser‘); ... app.use(cookieParser(‘this is the secret key for singed cookie‘)); ...
js路由中使用比较简单:
router.post("/setCookie",function(req,res, next){ var addr = req.body.a; //设置cookie,配置signed: true的话可以配置签名cookie res.cookie("addr", addr, {maxAge: 1000*60*60*24*30,httpOnly: true}); //, signed: true next(); });
//获取cookievar a = req.cookies.addr;//var a = req.signedCookies[‘addr‘]; 获取签名cookie console.log(a);
session
app.js配置:
... var session = require("express-session"); var cookieParser = require(‘cookie-parser‘); ... app.use(session({ secret: ‘this is the secret for cookie‘, resave: false, saveUninitialized: true })); app.use(function (req, res, next) { var url = req.originalUrl; if (url != "/" && undefined == req.session.user) { if(url != "/create/article"){ //排除/create/article路由的session拦截 res.send(‘<script>top.location.href="/";</script>‘); return; } } next(); });
在路由中直接通过如下设置或者获取session数据:
var user = req.session.user; console.dir(user);
session的清除:
req.session.destroy(function(err) { res.redirect(‘/‘); })
时间: 2025-01-01 10:18:32