调用OpenWeatherMap API遇400错误:lat/lon为undefined求助
问题原因与修复方案:OpenWeatherMap API 400 Bad Request(lat/lon为undefined)
问题根源
你的代码存在异步流程控制混乱的问题:
- 调用
fetch_begin_for_LINK_API.json()后得到的是Promise对象,你用.then()来赋值lat和lon,但这个回调是异步执行的,不会阻塞后续代码。 - 后面的天气API请求直接跳过等待,在
lat和lon还没被赋值(依然是初始的undefined)时就发起了,导致请求参数无效,返回400错误。 - 既然已经用了
async/await,就没必要混用.then(),这会彻底打乱异步代码的执行顺序。
修复步骤
- 用
await等待地理数据的解析结果,确保lat和lon被正确赋值后,再发起天气API请求。 - 增加基础错误处理,避免请求失败或返回数据为空时出现无意义的报错。
修正后的代码
"use strict"; const API_KEY = "myKey"; const GEO_API_LINK = "http://api.openweathermap.org/geo/1.0/direct?q=berlin"; const WEATHER_API_LINK = "https://api.openweathermap.org/data/2.5/weather"; const fetchFunc = async function () { try { // 1. 获取地理坐标,用await等待解析完成 const geoResponse = await fetch(`${GEO_API_LINK}&appid=${API_KEY}`); if (!geoResponse.ok) throw new Error("地理坐标请求失败"); const geoData = await geoResponse.json(); if (!geoData || geoData.length === 0) throw new Error("未获取到目标城市坐标"); const lat = geoData[0].lat; const lon = geoData[0].lon; // 2. 确保坐标赋值完成后,发起天气API请求 const weatherResponse = await fetch(`${WEATHER_API_LINK}?lat=${lat}&lon=${lon}&appid=${API_KEY}`); if (!weatherResponse.ok) throw new Error("天气数据请求失败"); const weatherData = await weatherResponse.json(); console.log(weatherData); } catch (err) { console.error("请求出错:", err.message); } } fetchFunc();
额外优化说明
- 把变量名改成更语义化的名称(比如
GEO_API_LINK、WEATHER_API_LINK),提升代码可读性。 - 用
const替代不必要的let,符合JS最佳实践。 - 添加
try/catch捕获异步请求中的错误,方便快速排查问题。
内容的提问来源于stack exchange,提问作者Marco1314
相关产品推荐
相关产品推荐

