You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用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(),这会彻底打乱异步代码的执行顺序。

修复步骤

  1. 用await等待地理数据的解析结果,确保lat和lon被正确赋值后,再发起天气API请求。
  2. 增加基础错误处理,避免请求失败或返回数据为空时出现无意义的报错。

修正后的代码

"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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:20:06