【项目心得】在nest中使用fastify-cookie

包安装

确保你在nest项目中安装了 fastify, @fastify/cookie, @nestjs/platform-fastify 等包

npm i fastify @fastify/cookie @nestjs/platform-fastify

 

fastify的引入和fastify-cookie的注册

src/main.ts

复制代码
async function bootstrap() {

  const logger: Logger = new Logger('main', {})

  // @ts-ignore
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter(), {
    logger: IS_DEV ? ['log', 'debug', 'error', 'warn'] : ['error', 'warn']
  })
await app.register(fastifyCookie, { secret:
'my-secret' })
app.useLogger(await app.resolve(Logger)) await app.listen(PORT, ()
=> { logger.log(`${ENVNAME} Server is running, interface load on: http://localhost:${PORT}${PREFIX}`) }) }
复制代码

 

使用

写入cookie

复制代码
@Get()
  async pushCode(@Res({passthrough: true}) res: FastifyReply): Promise<BaseResponser> {
    // return this.verifyService.pushCode()

    var nowDate: Date = new Date()
    nowDate.setSeconds(nowDate.getSeconds() + 60)

    var result = await this.verifyService.pushCode()
    // 写入Cookie
    res.setCookie("captcha", result.data.text, {
      path: '/',
      expires: nowDate
    })
    return {
      ok: result.ok,
      data: result.data.data
    }
  }
复制代码

读取cookie

@Post()
  async copeCode(@Req() request: FastifyRequest): Promise<BaseResponser> {
    return {
      ok: true,
      data: request.cookies // or request.cookies[key]
    }
  }

 

posted @   SILL  阅读(158)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示