JavaScript调用OpenWeatherMap预报API出现undefined错误如何解决
OpenWeatherMap预报API返回undefined报错排查方案
核心问题根因
你编写的预报API请求逻辑本身可正常运行,出现undefined报错是因为预报接口与实时天气接口的返回JSON结构不通用,复用实时天气的字段读取路径时会找不到对应属性,进而抛出undefined错误。
两个接口的结构差异如下:
- 实时天气
/weather接口:天气相关字段直接挂载在返回数据根节点下,你原有代码的data.weather[0]、data.main.temp读取路径完全匹配接口结构 - 预报
/forecast接口:所有预报数据存放在返回数据根节点的list数组内,你传入了cnt=1参数仅返回1条预报,对应正确的读取路径应为data.list[0].weather[0]、data.list[0].main.temp
调试小技巧
遇到接口返回undefined问题时,可以先打印完整的返回数据,查看实际字段层级:
// 临时打印完整返回结构排查字段 .then(data => { console.log('完整预报返回数据:',data) })
修复后完整可运行代码
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 => this.displayForecast(data)); }, displayForecast: function(data){ // 新增一层list[0]路径匹配预报接口结构 const{icon,description} = data.list[0].weather[0]; const{temp} = data.list[0].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; } }; // 调用测试 // inOneDay.fetchWeather();
内容的提问来源于stack exchange,提问作者Nabil El Hajji Lara
相关产品推荐
相关产品推荐

