【问题标题】:node-fetch "api key is not a legal HTTP header" errornode-fetch "api key is not a legal HTTP header" 错误
【发布时间】: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


【解决方案1】:

我在 nextjs 遇到了同样的问题和同样的错误,我将 url_list[url] 替换为 encodeURI(url_list[url])如下

 return NextResponse.redirect(
            encodeURI(url_list[url]),
            301
        )

编码网址解决了我的问题

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 2015-02-15
    • 2022-01-16
    • 2020-01-03
    • 2021-08-04
    相关资源
    最近更新 更多