Cookie的使用
express中使用cookie的话,需要引入cookie-parser模块。步骤如下
1 安装 npm install cookie-parser --save
2.引入 const cookParser = require('cookie-parser');
3.设置中间件
app.use(cookParser());
4.设置cookie
前两个参数为cookie的键值,第三个参数为一个对象,可以设置cookie各种属性
res.cookie("name","zlfan",{maxAge: 1000*60*60})
5.获取cookie
req.cookies.name
例子app.js:
const express = require('express');
const cookParser = require('cookie-parser');
const app = express();
app.use(cookParser())
app.get('/',(req,res)=>{
res.cookie("name","zlfan",{maxAge: 1000*60*60})
res.send("设置cookie");
})
app.get('/getCookie',(req,res)=>{
const name = req.cookies.name;
res.send("获取到cookie:"+name);
console.log(name);
})
app.listen(3000)
res.cookie()
第三个参数的相关属性见下表:
属性 | 说明 |
---|---|
domain | 作用:多个域名共享cookie,如设置domin为.zlfan.com ,则 aaa.zlfan.com 和 bbb.zlfan.com 这两个域名均可以访问cookie |
Expires | 过期时间(秒),在设置的某个时间点后该 Cookie 就会失效,如 expires=Wednesday,09-Nov-99 23:12:40 GMT |
maxAge | 最大失效时间(毫秒),设置在多少时间后失效 |
secure | 当 secure 值为 true 时,cookie 在 HTTP 中是无效,在 HTTPS 中才有效 |
Path | 表示 cookie 影响到的路径,如 path=/temp,只有这个路径能访问到cookie |
httpOnly | 默认是false ,当为true 时,只能服务器端进行获取,JS等前端语言无法获取cookie |
singed | 表示是否签名加密 cookie, 设为 true 会对这个 cookie 签名,在使用中间件时传入加密参数app.use(cookParser('zlfan')) ,这样就需要用res.signedCookies 而不是 res.cookies 访问它。被篡改的签名 cookie 会被服务器拒绝,并且 cookie值会重置为它的原始值。 |
cookie的删除:
express直接提供了api删除浏览器中的cookie:
function(req, res, next){
...
res.clearCookie(name [, options]);
...
}
clearCookie()
第一个参数接收cookie的name,如res.clearCookie('name')