18910140161

JavaScript-天气应用程序的API值-未捕获类型错误-堆栈溢出

顺晟科技

2022-10-18 12:08:17

81

我觉得这是一个愚蠢的问题,但我试图学习更多关于使用JavaScript的API.我正在使用开放天气应用程序的API.

我的项目的

一部分将允许用户在表单中输入一个城市,然后API获得当前天气/当前温度等。这部分工作完全正常。

我正在尝试制作一个页面,允许用户在表单中输入一个城市,然后显示未来几天的天气预报。

它无法识别API中的值。我相信我在网站上使用了正确的文档,这里是:https://openweathermap.org/forecast16。

我正在使用FETCH,它正在被调用,但值是“未定义的”我得到未捕获的TypeError:无法读取未定义的属性“ temp ”。

下面是URL和部分JS代码:

<代码>const API=`https://api.openweathermap.org/data/2.5/forecast/daily?。Q=${input}&;CNT=2&;Lang=en&;appid=${mykey}&;单位=公制`;填充UI(数据){this.uicontainer.innerHTML=`<;DIV类=";卡片MX-AUTO MT-5";style=";宽度:18rem;";>;<;DIV类=";卡体公正内容中心";>;<;H5类=";卡片标题";>;${data.name}<;/H5>;<;p类=";卡片字幕MB-2文本静音";>;${data.list.temp.min}的最大值。的低点${data.list.temp.Max}<;/p>;<;p类=";卡片文本";>;天气状况描述为:${data.list.weather.description}<;/p>;<;p类=";卡片文本";>;感觉像:${data.list.Feels_像}<;/p>;<;p类=";卡片文本";>;风速:${data.list.humidity}m/s<;/p>;<;/DIV>;<;/DIV>;`; }

如果我将${data.list}用于所有这些,我得到401(未授权),所以我不确定我的URL是否是错误的,但由于文档的原因,它看起来是正确的。我是否需要为天气预报生成第二个API密钥,因为我已经有了站点当前天气部分的API密钥?


顺晟科技:

根据文档中的示例JSON结构,const api = `https://api.openweathermap.org/data/2.5/forecast/daily? q=${input}&cnt=2&lang=en&appid=${myKey}&units=metric`; populateUI(data) { this.uiContainer.innerHTML = ` <div class="card mx-auto mt-5" style="width: 18rem;"> <div class="card-body justify-content-center"> <h5 class="card-title">${data.name}</h5> <p class="card-subtitle mb-2 text-muted">Highs of ${data.list.temp.min}. Lows of ${data.list.temp.max}</p> <p class="card-text ">Weather conditions are described as: ${data.list.weather.description}</p> <p class="card-text ">Feels like: ${data.list.feels_like}</p> <p class="card-text ">Wind speed: ${data.list.humidity} m/s</p> </div> </div> `; } 是一个对象数组,每个对象都包含list等属性。(参见https://openweathermap.org/forecast16#json

要在代码中访问此类属性,应遍历temp中的项并从每个项中获取属性。例如:

data.list
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航