【问题标题】:How to fix 404 while fetching如何在获取时修复 404
【发布时间】:2021-08-17 19:27:44
【问题描述】:

好的,我正在使用 openweather API 开发一个简单的 API 项目并制作我自己的项目,但是当我尝试从 API 获取数据时遇到了404 错误

这是我的代码:

async function fetchData(cityName) {
  const API_KEY = 'MY_API_KEY';

  const fethRes = await fetch(
    `api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`,
    {
      mode: 'cors',
    }
  );
}

这是我得到的错误

GEThttp://127.0.0.1:5500/dist/api.openweathermap.org/data/2.5/weather?q=paris&appid={MY_API_KEY}

出于安全原因,我隐藏了我的 api 密钥,希望您理解:)

【问题讨论】:

  • 尝试使用 'https://' 而不是 'api.'。或者,也许您需要离开“api”。只需在前面添加“https://”即可。
  • @CharlesEF 仍然面临同样的问题
  • Fetch 使用您的 url 作为域。你需要做fetch(https://api.openweathermap.org/......)
  • @StevenB。仍然面临同样的问题,我应该提供一些错误快照吗?

标签: javascript api async-await promise fetch


【解决方案1】:

已更新,我已经测试了代码,现在可以运行了

async function fetchData(cityName) {
  const API_KEY = 'Your_API_KEY';

const fethRes =  {
  method: 'GET',
  redirect: 'manual'
};

await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`, fethRes)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多