调用OpenWeatherMap API时出现JSON.parse错误的排查求助
解决OpenWeatherMap API调用的JSON解析错误
你遇到的错误 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data App.js:27,问题出在预报API的URL缺少https://前缀,具体分析和修复如下:
错误原因
看你代码里的fetchForecast请求:
const fetchForecast = fetch( `api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&appid=${WEATHER_API_KEY}` );
这个URL没有https://前缀,浏览器会把它当成当前域名下的相对路径去请求,返回的不是OpenWeatherMap的JSON数据,而是404页面的HTML内容(第一个字符是<)。当你在第27行调用.json()时,JSON解析器无法处理HTML,就会抛出“第1行第1列字符异常”的错误——这里的“第1行第1列”指的是API响应内容的位置,不是你的代码行,错误提示里的App.js:27只是触发错误的代码行。
修复方案
给预报API的URL加上https://前缀:
const fetchForecast = fetch( `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&appid=${WEATHER_API_KEY}` );
额外建议
为了避免类似问题,建议在解析JSON前先检查请求是否成功:
Promise.all([fetchCurrentWeather, fetchForecast]) .then(async (responses) => { const [weatherRes, forecastRes] = responses; // 检查HTTP状态是否正常 if (!weatherRes.ok) throw new Error(`天气请求失败: ${weatherRes.status}`); if (!forecastRes.ok) throw new Error(`预报请求失败: ${forecastRes.status}`); const weatherResponse = await weatherRes.json(); const forecastResponse = await forecastRes.json(); setCurrentWeather({ city: searchData.label, ...weatherResponse }); setForecast({ city: searchData.label, ...forecastResponse }); }) .catch((err) => console.log(err));
这样能提前捕获HTTP错误,更容易排查问题。
内容的提问来源于stack exchange,提问作者downmath
相关产品推荐
相关产品推荐

