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

使用OpenWeather API开发天气应用遇401错误及数据异常求助

问题解决思路

核心错误原因

  • API Key 变量名与语法错误:模板字符串里写的是$(apikey),但你定义的变量是apiKey(JS变量大小写敏感),且模板字符串的正确语法是${变量名}而非$(),这导致请求未携带有效API Key,触发401错误。
  • 未处理请求失败场景:当请求返回错误时,data中不会包含name、main、wind等属性,直接访问这些属性会返回undefined,造成页面显示异常。

修正后的代码

<script>
  const apiKey = "c783c8739883eb8cfbb8e5fb0a959dc5";
  const apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=metric&q=";
  const searchBox = document.querySelector(".search input");
  const searchBtn = document.querySelector(".search button");

  async function checkweather(city) {
    try {
      const response = await fetch(apiUrl + city + `&appid=${apiKey}`);
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      const data = await response.json();
      console.log(data);
      // 先判断属性是否存在,避免显示undefined
      document.querySelector(".city").innerHTML = data.name || "未知城市";
      document.querySelector(".temp").innerHTML = data.main 
        ? Math.round(data.main.temp) + "°c" 
        : "--";
      document.querySelector(".humidity").innerHTML = data.main 
        ? data.main.humidity + "%" 
        : "--";
      document.querySelector(".windspeed").innerHTML = data.wind 
        ? data.wind.speed + "km/h" 
        : "--";
    } catch (error) {
      console.error(error);
      // 请求失败时统一显示占位符
      document.querySelector(".city").innerHTML = "城市不存在或请求错误";
      document.querySelector(".temp").innerHTML = "--";
      document.querySelector(".humidity").innerHTML = "--";
      document.querySelector(".windspeed").innerHTML = "--";
    }
  }
  searchBtn.addEventListener("click", () => {
    checkweather(searchBox.value.trim()); // 去除输入的前后空格,避免无效请求
  });
</script>

关键修正点

  1. 修复API Key的模板字符串语法:将$(apikey)改为${apiKey},确保变量正确注入请求链接。
  2. 添加try/catch捕获请求错误,处理网络异常或API返回错误的场景。
  3. 对data的属性做存在性判断,避免直接访问不存在的属性导致undefined。
  4. 给搜索输入值添加trim(),防止用户输入空格引发无效请求。

内容的提问来源于stack exchange,提问作者Emeka a1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:32:42