nodejs cookie 使用

1.基本配置

1.下载cookie

npm install cookie-parse --save

 2.引入cookie

var cookieParser=require('cookie-parser')

3.配置中间件

 app.use(cookieParser('itying'))

这里面的itying是随便写的,是给加密用的

 2.写入cookie

username:表示字段名

zhangsan:表示字段值

{}:这里面的是配置信息

{maxAge:1000*60}:表示1分钟后失效

{signed:true}:表示要进行加密

app.get('/index',function(req,res){

    res.cookie('username','zhangsan',{maxAge:1000*60}) // 设置cookie

    res.send('你好 express')

    res.end()

})

 

 访问http://localhost:8090/indexindex即可写入成功

 3.访问cookie

app.get('/login',(req,res)=>{

let username=req.cookies.username;  // 获取cookie

console.log(username);

res.send('name is '+username)

   res.end()

})

 通过访问:http://localhost:8090/login 即可读取

 

4.写入加密的cookie

app.use(cookieParser('itying'))//中间件里要写点东西,随便写点

app.get('/index',function(req,res){

    res.cookie('username','zhangsan',{maxAge:1000*60,signed:true})   // signed:true设置加密的cookie

    res.send('你好 express')

    res.end()

})

 图片可看出加密了

 5.读取加密的cookie

app.get('/product',(req,res)=>{

let username=req.signedCookies.username;// 获取加密cookie

console.log(username);

res.send('name is '+username)

   res.end()

})

 虽然加密了但还是可以读取

而且你给他改了,会显示false

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值