如何在 Open Weather API 上使用 fetch api 方法

How to use the fetch api method on Open Weather API

我正在尝试使用 fetch 方法在网站上显示当前天气。但是,我不断收到一条错误消息,指出 res 未定义。我需要做什么?

fetch('https://api.openweathermap.org/data').then(res => {
     return res.json();
}).then(function(myJson) {
     console.log(res.coord);
});

注意:API 调用已被编辑以确保隐私

问题是您在函数中使用了不同的参数名称。在您的第一个函数中,您使用的是 res:

.then(res => { 

但是在你的第二个,你正在使用 myJSON:

.then(function(myJson) {

将您的代码更改为这样可以解决您的问题:

fetch('https://api.openweathermap.org/data').then(res => {
     return res.json();
}).then(function(res) {
    console.log(res.coord);
});