如何解决OpenWeather API 未使用 Javascript 连接
我想显示我输入的州的天气状况,但它一直提示“错误的城市名称,然后显示未定义
var button =document.querySelector('.button')
var inputValue =document.querySelector('.inputValue')
var nam =document.querySelector('.nam');
var desc =document.querySelector('.desc');
var temp =document.querySelector('.temp');
button.addEventListener('click',function(){
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue.value+'&appid=0c712e338cabb3996a78ae788fa566a1')
.then(response=> response.json())
.then(data => {
var nameValue = data['nam'];
var temp = data['main']['temp'];
var descValue = data['weather'][0]['description'];
nam.innerHTML =nameValue;
temp.innerHTML =tempValue;
desc.innerHTML =description;
})
.catch(err => alert("Wrong City name!"))
})
解决方法
如果您从 API [1] 收到错误响应,那么由于嵌套结构,您将在以下行的代码中抛出一些异常。
// "main" does not exist in error response,so you
// will get an error trying to access a child of "main".
var temp = data['main']['temp'];
// "weather" does not exist in error response,so you
// will get an error trying to access a child of "weather".
var descValue = data['weather'][0]['description'];
在尝试解析响应数据之前检查响应代码是一个好习惯,就像这样 -
.then(response => {
if (response.cod == 200) {
// Do your stuff
} else {
throw new Error(response.message)
}
).catch(err => alert(err))
除此之外,您的代码中还有几个拼写错误 -
// There is no key "nam" in the response,it is "name",see success response [2].
var nameValue = data['nam'];
// You save the description as "descValue"
var descValue = data['weather'][0]['description'];
// But use "description" here
desc.innerHTML =description;
[1] 错误响应 -
{
"cod": "404","message": "city not found"
}
[2] 成功响应(如果城市存在)-
{
"coord": {...},"weather": [...],"base": "stations","main": {...},"visibility": 10000,"wind": {...},"clouds": {...},"dt": 1618812226,"sys": {...},"timezone": -14400,"id": 4350049,"name": "California","cod": 200
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。