【发布时间】: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.authorization 或 req.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.authorization和req.headers.Authorization有不同的数据类型? - 我谷歌一下,所有关于授权的教程都使用
req.headers.authorization,那么req.headers.Authorization呢?
【问题讨论】:
标签: typescript express header apollo-server