nestjs - 如何使用 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/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",
};
}
}
推荐阅读
- scala - 在 spark scala 的数据框列中过滤 NULL 值
- ios - Firebase Messaging iOS - 首次运行多主题订阅的应用程序 1 失败
- git - git hooks如何在不同的操作系统上提供参数
- aframe - 开始:单击在 Aframe v 0.8.0 中不起作用
- ios - 将 CVImageBuffer 扭曲到 UIImage
- java - 使用 Java 的无限对象?
- javascript - 用JS重复值和替换值
- sql - 如何编写 sql 以在 Postgres 中生成每个客户的月累计销售额
- dialogflow-es - Google Home 发送 GET 请求并说出响应
- c# - 从字符串调用方法作为继承类