当前位置: 首页 > 工具软件 > core-nestjs > 使用案例 >

5.nestjs cookie的配置和使用

那谦
2023-12-01

安装和配置

1. 安装

npm install cookie-parser --save

2. 配置

2.1 main.ts 中引入 cookie-parser

import * as cookieParser from 'cookie-parser' 

2.2. main.ts 配置中间件

app.use(cookieParser()); 

3.设置cookie

res.cookie('username', 'aabbcc我是cookie', {maxAge: 1000*60*10, httpOnly: true})

4.获取cookies

@Get('cookie')
getCookie(@Request() req){
    console.log(req.cookies.username);
    return req.cookies.username;
}

cookie加密

1.main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { join } from 'path';
import * as cookieParser from 'cookie-parser';

async function bootstrap() {
  // ...
  
  // 配置cookie中间件,()里面写上东西
  app.use(cookieParser('this signed cookies'));
  await app.listen(3000);
}
bootstrap();

2. 在article.controller中添加加密cookie

import { Controller, Get, Response } from '@nestjs/common';
@Controller('article')
export class ArticleController {
    @Get()
    index(@Response() res){
        // 设置cookie,signed启用加密
        res.cookie('username', 'aabbcc我是cookie', {maxAge: 1000*60*10, httpOnly: true, signed: true})
        // 注:res和return不能同时使用,否则卡死
        // return '这是文章页面'; 
        res.send('这是文章页面');
    }
}

3.在user.controller中读取cookie

import { Body, Controller, Get, Post, Render, Response, Request } from '@nestjs/common';
@Controller('user')
export class UserController {
    // ...
    // 获取cookie
    @Get('cookie')
    getCookie(@Request() req){
        // 1. 获取普通cookie
        // console.log(req.cookies.username);

        // 2. 获取加密cookie
        console.log(req.signedCookies.username);
        return req.signedCookies.username;
    }
}
 类似资料: