【问题标题】:undefined error when fetching weather forecast api javascript获取天气预报 api javascript 时出现未定义的错误
【发布时间】:2021-11-09 04:22:35
【问题描述】:

我正在尝试获取天气预报 api json,就像我使用当前天气 api 所做的那样,但它似乎无法以我尝试的任何方式工作。

    let inOneDay = {
fetchWeather: function(){
    fetch("https://api.openweathermap.org/data/2.5/forecast?q=Dortmund&units=metric&cnt=1&appid=758fce6dd3722cf25cd213a13bbc5484"
    ).then(resp => resp.json())
    .then(data => console.log(data));
}

};

我不知道我哪里出错了。我使用相同的逻辑使下面的代码工作:

let weather = {
    fetchWeather: function(){
        fetch("https://api.openweathermap.org/data/2.5/weather?q=Dortmund&units=metric&appid=758fce6dd3722cf25cd213a13bbc5484"
        ).then((response) => response.json())
        .then((data) => this.displayWeather(data));
    },
    displayWeather: function(data){
        const{icon,description} = data.weather[0];
        const{temp} = data.main;
        document.querySelector(".icon").src = "https://www.openweathermap.org/img/wn/" + icon + ".png";
        document.querySelector(".celsius").innerText = Math.round(temp) + "°C";
        document.querySelector(".desc").innerText = description;
    }

}

感谢任何想法!

【问题讨论】:

    标签: javascript json fetch-api openweathermap


    【解决方案1】:

    检查来自该 API 的 json 回复,看起来 OP 代码需要的字段与服务提供的字段不同。

    const result = 
    {"cod":"200","message":0,"cnt":1,"list":[{"dt":1631577600,"main":{"temp":13.31,"feels_like":13.05,"temp_min":13.31,"temp_max":15.87,"pressure":1018,"sea_level":1018,"grnd_level":1007,"humidity":90,"temp_kf":-2.56},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":1.42,"deg":94,"gust":2.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2021-09-14 00:00:00"}],"city":{"id":2935517,"name":"Dortmund","coord":{"lat":51.5167,"lon":7.45},"country":"DE","population":588462,"timezone":7200,"sunrise":1631595820,"sunset":1631641686}};
    
    const result0 = result.list[0];        // notice .list[0]
    const weather0 = result0.weather[0];   // notice weather[0]
    const main = result0.main;             // notice main is a sibling prop to weather
    const temp = main.temp
    
    console.log(`weather is ${JSON.stringify(weather0)}`);
    console.log(`main is ${JSON.stringify(main)}`);
    console.log(`temp is ${temp}`);

    请务必在取消引用结果之前检查错误。看起来 api 还提供了一个 cnt 属性,它可能指示列表中元素的数量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 2022-01-16
      • 2011-11-15
      • 2016-01-27
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多