【问题标题】:Getting API authentication key error with PublicAPI使用 PublicAPI 获取 API 身份验证密钥错误
【发布时间】:2022-01-25 09:33:00
【问题描述】:

我是 FetchAPAI 的新手。对于我的第一个 API 项目,我目前正在使用 ClimatIQ API 并按照他们的快速入门guide 中的步骤进行操作。即使我已经注册并从他们那里收到了身份验证密钥,我也会不断收到他们的 ff 错误:

POST https://beta2.api.climatiq.io/estimate 400
{error: 'invalid_request', message: 'Error parsing the request body.'}

请注意指南中的代码,代码在 Curl 中,我尽了最大努力将该代码转换为 JavaScript 上的 fetchAPI 请求。

const fetchData = async (url) => {
  await fetch(url, {
    method: "POST",
    headers: { Authorization: "Bearer MY_API_KEY" },
    data: {
      emission_factor: "electricity-energy_source_grid_mix",
      parameters: {
        energy: 4200,
        energy_unit: "kWh",
      },
    },
    //body: JSON.stringify(data),
  })
    .then((response) => response.json())
    .then((json) => console.log(json))
    .catch((err) => console.log(`Here's the error ${err}`));
};

fetchData("https://beta2.api.climatiq.io/estimate");

有时,即使我已经在我的代码库的“MY_API_KEY”部分中输入了他们给我的身份验证密钥,它也会显示“未定义标头”。这是他们服务器的错误吗?

【问题讨论】:

    标签: javascript api public


    【解决方案1】:

    试试这个:

    const data = {
      emission_factor: "electricity-energy_source_grid_mix",
      parameters: {
        energy: 4200,
        energy_unit: "kWh",
      },
    };
    
    const fetchData = async(url) => {
      await fetch(url, {
          method: "POST",
          headers: {
            Authorization: "Bearer MY_API_KEY",
            "Content-Type": "application/json"
          },
          body: JSON.stringify(data)
        })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((err) => console.log(`Here's the error ${err}`));
    };
    
    fetchData("https://beta2.api.climatiq.io/estimate");
    

    【讨论】:

    • 你真是太棒了!太感谢了。从现在开始,我真的需要用那个标题部分来打磨它,并将它内化在我的脑海中。 :-/
    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2021-01-22
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多