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

我的天气应用调用OpenWeather API时出现400错误,该如何解决?

解决OpenWeather API 400错误的方案

核心问题分析

你的代码里有几个关键错误导致了400请求错误:

  • API URL初始化时机错了:页面刚加载时就用searchbar.value构建了apiURL,这时候搜索框是空的,导致请求的q(城市名)参数为空,直接触发API的参数无效错误。
  • 函数调用与拼写错误:提交事件里没调用getWeather函数,反而用了初始的空参数URL;另外getWeather里的apiURl是拼写错误(最后一个字母是大写L,应该是小写l)。

修复后的完整代码

把URL构建逻辑移到搜索提交时动态生成,同时修正拼写和调用问题:

const searchbar = document.querySelector('#search-bar');
const temperature = document.querySelector('.temperature');
const description = document.querySelector('.description');
const imageContainer = document.querySelector('.image-container');
const API_KEY = '<MY_API_KEY>';

document.querySelector('form').addEventListener('submit', (e) => {
  e.preventDefault();
  // 先获取当前搜索框的内容,再调用天气查询函数
  const cityName = searchbar.value.trim();
  if (cityName) {
    getWeather(cityName);
  }
});

async function getWeather(city) { 
  // 每次查询时动态构建带有效城市名的API URL
  const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`;
  const response = await fetch(apiURL);
  
  // 主动检查请求状态,方便排查问题
  if (!response.ok) {
    const errorData = await response.json();
    console.error('API请求错误:', errorData.message);
    return;
  }
  
  const data = await response.json();
  console.log(data);
  // 这里可以添加更新UI的代码,比如把温度、天气描述渲染到页面上
}

额外优化建议

  • 可以给空搜索加提示:如果用户没输入城市就提交,弹出提示避免无效请求
  • 处理API返回的城市不存在等错误,比如在控制台打印错误信息或者给用户友好提示

内容的提问来源于stack exchange,提问作者Zavier walton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:48:11