首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取天气预报api javascript时出现未定义错误

获取天气预报api javascript时出现未定义错误
EN

Stack Overflow用户
提问于 2021-09-13 23:21:03
回答 1查看 71关注 0票数 1

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

代码语言:javascript
复制
    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));
}

};

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

代码语言:javascript
复制
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;
    }

}

感谢您的任何想法!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-13 23:43:55

检查来自该API的json应答,看起来操作码期望的字段与服务提供的字段不同。

代码语言:javascript
复制
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属性,它可以指示列表中元素的数量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69170068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档