天气API应用四天预报无法输出问题求助
天气应用四天天气预报无数据问题排查与修复
问题描述
开发基于OpenWeatherMap API的天气应用时,四天天气预报无法正常输出:console.log(fourDaysForecast)无有效内容,调用createWeatherCard仅生成无数据的空卡片,API链接配置确认正确。
代码片段
JavaScript代码
const searchButton = document.getElementById("searchBtn"); const cityInput = document.getElementById("cityInput"); const weatherCardsDiv = document.getElementById("weather-cards"); const API_KEY = "d292bd950ad1111c4da438d7967f0848"; const createWeatherCard = (weatherItem) => { return` <div class="bg-slate-400 rounded p-3 card"> <div class="border border-dashed border-2 border-slate-900 rounded p-4"> <div class="text-center font-bold">(${weatherItem.dt_txt.split(" ")[0]})</div> <div class="relative mb-4"> <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="cloud" class="w-[5rem] m-auto"> <h4 class="text-center">Moderate Rain</h4> </div> <div class="flex justify-between mb-2"> <h4>Temp -</h4> <p class="text-xl font-bold mb-px">${(weatherItem.main.temp - 273.15).toFixed(2)}*C</p> </div> <div class="flex justify-between mb-2"> <h4>Wind -</h4> <p class="text-xl font-bold mb-px">${weatherItem.wind.speed} M/S</p> </div> <div class="flex justify-between "> <h4>Humidity -</h4> <p class="text-xl font-bold mb-px">${weatherItem.item.main.humidity}%</p> </div> </div> </div> `; } const getWeatherDetails = (cityName, lat, lon) => { const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_KEY}`; fetch(WEATHER_API_URL).then(res => res.json()).then(data => { const uniqueForecastDays = []; const fourDaysForecast = data.list.filter(forecast => { const forecastDate = new Date(forecast.dt_txt).getDate(); if(!uniqueForecastDays.includes(forecastDate)) { return uniqueForecastDays.push(forecastDate); } }); cityInput.value = ""; weatherCardsDiv.innerHTML = ""; console.log(fourDaysForecast); fourDaysForecast.forEach(weatherItem => { weatherCardsDiv.insertAdjacentHTML("beforeend", createWeatherCard(weatherItem)); }) }).catch(() => { // alert("An error occurred when fetching the data"); }); } const getCity = () => { const cityName = cityInput.value.trim(); if(!cityName) return; const GEOCODING_API_URL = `http://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`; fetch(GEOCODING_API_URL).then(res => res.json()).then(data => { if(!data.length) return alert(`No Data found for ${cityName}`); const { name, lat, lon} = data[0]; getWeatherDetails(name, lat, lon); }).catch(() => { alert("An error occurred while fetching the data") }); } searchButton.addEventListener("click", getCity); searchButton.click();
HTML代码
<label for="cityInput">City</label> <input id="cityInput" type="text" value="Rome"> <input type="button" id="searchBtn" value="Search"> <div id="weather-cards"></div> <script src="https://cdn.tailwindcss.com"></script>
问题分析与修复
1. 日期过滤逻辑错误
filter回调中,uniqueForecastDays.push(forecastDate)返回数组新长度(数字类型),虽能通过truthy值保留当前项,但未限制获取4天数据,且跨月时日期号重复会导致过滤异常;同时filter需明确返回布尔值,避免隐式类型转换问题。
修复后代码:
const fourDaysForecast = data.list.filter(forecast => { const forecastDate = new Date(forecast.dt_txt).getDate(); if(!uniqueForecastDays.includes(forecastDate) && uniqueForecastDays.length < 4) { uniqueForecastDays.push(forecastDate); return true; } return false; });
2. 湿度字段访问错误
createWeatherCard中湿度字段错误写成weatherItem.item.main.humidity,正确路径应为weatherItem.main.humidity(多了冗余的.item层级),导致无法获取湿度数据甚至中断渲染。
修复后代码:
<p class="text-xl font-bold mb-px">${weatherItem.main.humidity}%</p>
3. 天气描述硬编码
原代码中天气描述为固定值,需改为从API返回数据中读取:
修复后代码:
<h4 class="text-center">${weatherItem.weather[0].main}</h4>
完整修复后的JavaScript代码
const searchButton = document.getElementById("searchBtn"); const cityInput = document.getElementById("cityInput"); const weatherCardsDiv = document.getElementById("weather-cards"); const API_KEY = "d292bd950ad1111c4da438d7967f0848"; const createWeatherCard = (weatherItem) => { return` <div class="bg-slate-400 rounded p-3 card"> <div class="border border-dashed border-2 border-slate-900 rounded p-4"> <div class="text-center font-bold">(${weatherItem.dt_txt.split(" ")[0]})</div> <div class="relative mb-4"> <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="${weatherItem.weather[0].description}" class="w-[5rem] m-auto"> <h4 class="text-center">${weatherItem.weather[0].main}</h4> </div> <div class="flex justify-between mb-2"> <h4>Temp -</h4> <p class="text-xl font-bold mb-px">${(weatherItem.main.temp - 273.15).toFixed(2)}°C</p> </div> <div class="flex justify-between mb-2"> <h4>Wind -</h4> <p class="text-xl font-bold mb-px">${weatherItem.wind.speed} M/S</p> </div> <div class="flex justify-between "> <h4>Humidity -</h4> <p class="text-xl font-bold mb-px">${weatherItem.main.humidity}%</p> </div> </div> </div> `; } const getWeatherDetails = (cityName, lat, lon) => { const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_KEY}`; fetch(WEATHER_API_URL).then(res => res.json()).then(data => { const uniqueForecastDays = []; const fourDaysForecast = data.list.filter(forecast => { const forecastDate = new Date(forecast.dt_txt).getDate(); if(!uniqueForecastDays.includes(forecastDate) && uniqueForecastDays.length < 4) { uniqueForecastDays.push(forecastDate); return true; } return false; }); cityInput.value = ""; weatherCardsDiv.innerHTML = ""; console.log(fourDaysForecast); fourDaysForecast.forEach(weatherItem => { weatherCardsDiv.insertAdjacentHTML("beforeend", createWeatherCard(weatherItem)); }) }).catch(() => { alert("An error occurred when fetching the weather data"); }); } const getCity = () => { const cityName = cityInput.value.trim(); if(!cityName) return; const GEOCODING_API_URL = `http://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`; fetch(GEOCODING_API_URL).then(res => res.json()).then(data => { if(!data.length) return alert(`No Data found for ${cityName}`); const { name, lat, lon} = data[0]; getWeatherDetails(name, lat, lon); }).catch(() => { alert("An error occurred while fetching the geocoding data") }); } searchButton.addEventListener("click", getCity); searchButton.click();
内容的提问来源于stack exchange,提问作者Peace Akaehomen
相关产品推荐
相关产品推荐

