【问题标题】:fetch issue using OpenWeatherMap使用 OpenWeatherMap 获取问题
【发布时间】:2021-04-05 18:02:21
【问题描述】:

我尝试了各种方法从开放天气中获取天气数据 如果我将其粘贴到浏览器中,我会得到数据 http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a

但如果我将它与 fetch 或 Axios 或其他适用于我的其他 API 的方法一起使用,我将一无所获。谁能告诉我我做错了什么?谢谢

【问题讨论】:

  • 谢谢大家 - 似乎没有 https 是问题(我正在使用 repl.it)
  • 是的,它工作正常。

标签: javascript api fetch weather


【解决方案1】:

index.html

<html lang="en">

<head>
    <title>Document</title>
</head>

<body>

</body>

<script>
    fetch('http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a')
        .then(data => data.json())
        .then(data => {
            console.log(data);
        })
</script>

</html>

【讨论】:

    【解决方案2】:

    使用 https 而不是 http。您将获得数据。

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        试试这个

        const response = await fetch("http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a");
        
        const data =  await response.json();
        
        console.log(data);
        

        还将您的代码包装在 try/catch 中以捕获任何可能的错误。

        你也可以使用 Promise 代替 async/await -

        fetch("http://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a")
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => {
          console.log(error);
        });
        

        如果您提供您已经在问题中尝试过的解决方案,那会更好。

        【讨论】:

        • 谢谢 - 它只是在 URL 中没有 https - 我正在尝试您提供的相同代码。仅http对您有用吗?我正在使用 REPL 在线 IDE,所以这可能是一个因素
        • 我在浏览器控制台中试过,没有 https 也能正常工作。
        猜你喜欢
        • 1970-01-01
        • 2021-12-31
        • 2021-05-11
        • 2019-04-23
        • 2022-08-06
        • 2015-10-06
        • 2021-11-27
        • 2016-06-22
        • 1970-01-01
        相关资源
        最近更新 更多