【问题标题】:How does nestjs get the cookie in the request?nestjs 是如何获取请求中的 cookie 的?
【发布时间】:2019-03-13 08:04:49
【问题描述】:

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
  }
}

【问题讨论】:

    标签: nestjs


    【解决方案1】:
    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();
    

    【讨论】:

      【解决方案2】:

      你必须安装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

      【讨论】:

      • 如何在 e2e 测试中这样做
      猜你喜欢
      • 2021-10-18
      • 2019-06-20
      • 2014-12-09
      • 2020-10-21
      • 2020-07-10
      • 2016-03-17
      • 1970-01-01
      • 2014-04-11
      • 2019-10-09
      相关资源
      最近更新 更多