express中cookie的基本使用

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')



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值