nestjs如何获取请求中的cookie?

How does nestjs get the cookie in the request?

nestjs如何获取请求中的cookie?

import { Get, Controller, Response, Request } from '@nestjs/common';
import { AppService } from './app.service';

const l = console.log
@Controller()
export class AppController {
  @Get('json')
  json(@Request() req){
    console.log(req.cookies) // undefined
  }
}

您必须安装 cookie-parser 中间件。

$ npm install --save cookie-parser

安装过程完成后,只需将中间件绑定到您的应用程序即可:

const app = await NestFactory.create(ApplicationModule);
app.use(cookieParser());

在此处阅读更多内容:https://expressjs.com/en/resources/middleware/cookie-parser.html

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cookieParser());
  await app.listen(5000);
}
bootstrap();

对于 2022 年正在看这个问题的所有人。
您可以在文档中找到它: https://docs.nestjs.com/techniques/cookies

如果您使用 Typescript,其他答案无效。
您需要 运行(根据文档):

$ npm i cookie-parser
$ npm i -D @types/cookie-parser