首页 > 解决方案 > 如何使用 NestJS 获取请求标头?

问题描述

我有一个简单的应用程序,它Something: Value作为标题返回。我目前有以下作为控制器...

import { Controller, Get, Header } from "@nestjs/common";

@Controller("health")
export class HealthController {
  @Get()
  @Header("content-type", "application/json")
  checkHealth(): unknown {
    return {
      test: "This is the test",
    };
  }
}

在快递中,我希望能够做类似的事情,req.headers但我不知道如何在nestjs中做到这一点。

标签: nestjs

解决方案


您应该将来自 @nestjs/common 的 Headers 作为参数传递给函数:

import { Controller, Get, Headers } from "@nestjs/common";

@Controller("health")
export class HealthController {
  @Get()
  checkHealth(@Headers() headers: Record < string, string > ) {
    return {
      test: "This is the test",
    };
  }
}

如果您只需要一个标题,您可以将它的名称传递给标题,如下所示 @Headers('content-type') headers: string

或者,如果您想访问 express req 对象,您也可以将其传递给您的控制器

import { Controller, Get, Req } from "@nestjs/common";
import { Request } from 'express';

@Controller("health")
export class HealthController {
  @Get()
  checkHealth(@Req() req: Request) {
    return {
      test: "This is the test",
    };
  }
}

推荐阅读