包安装
确保你在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] } }
标签:nest,await,nowDate,cookie,fastify,data,app From: https://www.cnblogs.com/Tachibana-Yuki/p/17728098.html