主题
Cookie
默认 Express 适配器下,用 cookie-parser 解析请求。读取用 req.cookies,设置用 res.cookie(),删除用 res.clearCookie()。@Res({ passthrough: true }) 只补充响应头,返回值仍由 Nest 序列化。
bash
pnpm add cookie-parser
pnpm add -D @types/cookie-parser@types/cookie-parser 为 Express 的 Request 增加 cookies。
ts
import { NestFactory } from '@nestjs/core'
import cookieParser from 'cookie-parser'
import { AppModule } from './app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.use(cookieParser())
await app.listen(3000)
}
void bootstrap()ts
import { Controller, Get, Post, Req, Res } from '@nestjs/common'
import type { Request, Response } from 'express'
@Controller('session')
export class SessionController {
@Get()
read(@Req() req: Request) {
return { session: req.cookies.session }
}
@Post('login')
login(@Res({ passthrough: true }) res: Response) {
res.cookie('session', 'opaque-session-id', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 1000 * 60 * 60 * 24,
path: '/',
})
}
@Post('logout')
logout(@Res({ passthrough: true }) res: Response) {
res.clearCookie('session', { path: '/' })
}
}maxAge 的单位是毫秒。删除时 path、domain 须与设置时一致。
