我想显示我输入的状态的天气状况,但它一直在提醒"错误的城市名称,然后显示未定义的
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
}