nest cookies 使用

时间:2023-01-04 浏览:199 分类:NestJS

cookie可以用来存储用户信息,存储在客户端浏览器中,每次请求会带入cookie,常用于授权验证等,在实际项目中用的非常多。

安装依赖:

npm instlal cookie-parser --save 
npm i -D @types/cookie-parser --save


引入解析:

// main.ts

import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as cookieParser from 'cookie-parser'

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  
  //注册cookie
  app.use(cookieParser('dafgafa'));  //加密密码,也可以不用加
  
  await app.listen(3000);
}

bootstrap();


设置响应cookie:

请求该接口,响应并设置一个新cookie,使用 res.cookie() 方法

@Get()
async index(@Response() res){

    //设置cookie, signed:true加密
    //参数:1:key, 2:value, 3:配置
    await res.cookie('token', newSignedToken, {    
        domain,    // cookie 相应域名
        path: '/',    
        maxAge: 1800000,    
        httpOnly: true,    
        overwrite: false    
    });     
    
    //注意:
    //使用res后,返回数据必须使用res
    //如果是用了render模板渲染,还是使用return
    res.send({xxx})
}
  • 参数说明:

  • domain String 指定域名下有效

  • expires Date 过期时间(秒),设置在某个时间点后会在该cookoe后失效

  • httpOnly Boolean 默认为false 如果为true表示不允许客户端(通过js来获取cookie)

  • maxAge String 最大失效时间(毫秒),设置在多少时间后失效

  • path String 表示cookie影响到的路径,如:path=/如果路径不能匹配的时候,浏览器则不发送这个cookie

  • secure Boolean 当 secure 值为 true 时,cookie 在 HTTP 中是无效,在 HTTPS 中才有效

  • signed Boolean 表示是否签名cookie,如果设置为true的时候表示对这个cookie签名了,这样就需要用res.signedCookies()获取值cookie不是使用res.cookies()


获取cookie

使用 req.cookies() 方法获取 请求的cookie,此属性是一个包含请求发送的 cookie 的对象。如果请求不包含 cookie,则默认为 {}。

@Get()
index(@Request() req){
      console.log(req.cookies.username)
      
      //加密的cookie获取方式
      console.log(req.signedCookies.username)  
      return req.cookies.username
}

加密cookie 设置和获取

cookie 已经签名,则必须使用 req.signedCookies 获取

// 配置中间件的时候需要传参
app.use(cookieParser('123456'));

// 设置cookie的时候配置signed属性
res.cookie('userinfo','hahaha',{domain:'.ccc.com',maxAge:900000,httpOnly:true,signed:true});

// signedCookies调用设置的cookie
console.log(req.signedCookies);

删除cookie

使用 res.clearCookie() 方法清除现有 cookie

res.clearCookie('token', {    
    domain,    
    signed: false,    
    maxAge: 0,    
});