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

发布时间 2023-09-25 15:53:07作者: SILL

包安装

确保你在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]
    }
  }