【发布时间】:2021-10-28 04:00:29
【问题描述】:
我正在尝试使用 node-fetch 向外部 API 发出 GET 请求。当我运行代码时,出现以下错误:
UnhandledPromiseRejectionWarning: TypeError: Bearer [api key] is not a legal HTTP header value
不记名密钥是 JWT 格式,它位于外部配置文件中以保护隐私。
这是我的代码:
let api_config = require('./api_config.json');
const fetch = require("node-fetch");
fetch(api_config.API_Domain + api_config.SUBJECTCODES_OPTIONS_URI, {
method: 'GET',
headers: {
'Authorization': "Bearer " + api_config.API_Key,
"Content-type": "application/json",
"Accept": "application/json",
}
}).then(res => res.json())
.then(json => console.log(json))
【问题讨论】:
-
如果您的
API_Key值中包含行尾字符(CR 或LF),则会导致此问题。虽然不知道值(或它的混淆版本;例如,所有数字都替换为“A”,所有字母都替换为“B”,以保护实际值),这将是一场猜谜游戏。跨度> -
您也可能被阻止设置授权标头;有关这方面的更多信息,请参阅How to send authorization header with axios。
标签: javascript node.js api fetch-api node-fetch