【问题标题】:Typescript typing http headers打字稿键入 http 标头
【发布时间】:2021-05-31 12:56:12
【问题描述】:

我对 Typescript 及其类型定义建议感到非常困惑。我正在使用 Apollo Server 执行 Graphql API,并尝试通过请求标头使用 JWT 实现授权(我正在重写现有 API),所以首先我从请求标头中提取令牌:

const token: string = req.headers.authorization

但是这样做会引发错误,提示“类型 string | undefined 不能分配给类型 string" 所以我把它改成了:

const token: string | undefined = req.headers.authorization

好吧!但在原始 API 中,他们试图从 req.headers.authorizationreq.headers.Authorization 获取授权道具,我不知道为什么,但我尝试做同样的事情:

const token: string | undefined = req.headers.authorization || req.headers.Authorization

并得到一个新错误:“type string | string[] | undefined is not assignable to键入 字符串 | 未定义"

然后我又改成了:

const token: string | undefined | string[] = req.headers.authorization || req.headers.Authorization

我的问题:

  • 为什么req.headers.authorizationreq.headers.Authorization 有不同的数据类型?
  • 我谷歌一下,所有关于授权的教程都使用req.headers.authorization,那么req.headers.Authorization呢?

【问题讨论】:

    标签: typescript express header apollo-server


    【解决方案1】:

    1:为什么 req.headers.authorization 和 req.headers.Authorization 有不同的数据类型?

    你的答案在于here, in the TypeScript definitions for node's http library

    如您所见,req.headers.authorization 的定义如下:

    'authorization'?: string;
    

    因为它是可选的,所以它可以是undefined。否则,它是string

    现在寻找req.headers.Authorization 的定义位置。剧透警报,您不会在列表中找到它。这意味着您必须回顾 req.headers 的类型定义:

    interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
      ...other stuff
    }
    

    这意味着对于“其他东西”中未定义的任何字符串,类型可以是undefinedstringstring[]

    2:我google了一下,所有关于授权的教程都使用req.headers.authorization,那么req.headers.Authorization呢?

    根据 HTTP 规范,标头实际上是不区分大小写的。默认情况下,像 express(以及扩展 ApolloServer,它在 express 上运行)之类的东西会为您小写,因此您通常应该使用 req.headers.authorization

    奖金

    如果您曾经使用过apollo-server-lambda,出于某种原因(可能是AWS 的原因?)会保留大写字母,因此您必须使用event.headers.Authorization。这意味着如果你要在一个通用空间中做一些可以在不同 ApolloServer 实现之间交换的事情,你最好在两个地方都查看,接受undefined | string | string[],然后检查它是否是一个数组并使用第一个元素。

    不相关的[希望有帮助]语义

    const token: string | undefined | string[] = req.headers.authorization || req.headers.Authorization
    

    变量名token技术上不应该是准确的。授权标头应该是Authorization: &lt;type&gt; &lt;credentials&gt;。如果您正在寻找“令牌”,它可能在标题中,在 Bearer 之后。不是每个人都遵循这一点,但你通常可以在空间上分割并取最后一块,除非你真的想要整个标题,在这种情况下,忽略这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-02
      • 2020-05-21
      • 2020-08-21
      • 2019-11-28
      • 2020-02-22
      • 2019-04-07
      • 1970-01-01
      • 2021-03-09
      相关资源
      最近更新 更多