使用 OpenWeatherMap

问题描述

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

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

解决方法

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

,

这是正确的格式:

https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&units=metric&apikey="+key

将 http 改为 https

,

试试这个

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 中以捕获任何可能的错误。

你也可以使用 promises 代替 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);
});

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

,

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>