Nestjs中使用Cookie

43 阅读1分钟

安装

$ npm i cookie-parser
$ npm i -D @types/cookie-parser

引入

在main.ts中引入cookie-parser

import * as cookieParser from 'cookie-parser'

 app.use(cookieParser());

设置、获取、删除Cookies

HttpOnly 默认false不允许 客户端脚本访问

// 设置
getHello(@Res({ passthrough: true }) res) {
   res.cookie("name",'zhangsan',{maxAge: 900000, httpOnly: true}); 
   return this.appService.getHello();
}

//获取/////////////////////////////////////////
@Get('getCookies')    
getCookies(@Req() req){
   return req.cookies.name;
}

//删除////////////////////////////////////////
res.cookie('rememberme', '', { expires: new Date(0)});
res.cookie('username','zhangsan',{domain:'.ccc.com',maxAge:0,httpOnly:true});

参数

  • domain: 域名
  • expires: 过期时间(秒),在设置的某个时间点后该 Cookie 就会失效,如 expires=Wednesday, 09-Nov-99 23:12:40 GMT
  • maxAge: 最大失效时间(毫秒),设置在多少后失效
  • secure: 当 secure 值为 true 时,cookie 在 HTTP 中是无效,在 HTTPS 中才有效
  • path: 表示 cookie 影响到的路,如 path=/。如果路径不能匹配时,浏览器则不发送这个Cookie
  • httpOnly:是微软对COOKIE做的扩展。如果在COOKIE中设置了“httpOnly”属性,则通过程序(JS脚本、applet等)将无法读取到COOKIE信息,防止XSS攻击产生
  • signed:表示是否签名cookie, 设为true 会对这个cookie 签名,这样就需要用res.signedCookies而不是res.cookies访问它。被篡改的签名cookie 会被服务器拒绝,并且cookie 值会重置为它的原始值
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });

Cookie加密

  1. 配置中间件的时候需要传参

app.use(cookieParser(‘123456’));

  1. 设置cookie的时候配置signed属性

res.cookie(‘userinfo’,‘hahaha’,{domain:’.ccc.com’,maxAge:900000,httpOnly:true,signed:true});

  1. signedCookies调用设置的cookie

console.log(req.signedCookies);