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

无法从天气API获取数据,输入城市名触发400 Bad Request错误(JS)

Fixing the 400 Bad Request Error for OpenWeatherMap API

Let’s break down exactly why you’re hitting that 400 error and how to fix it step by step:

  • Primary Issue: Unencoded City Name Input
    The most common trigger for this 400 error is unhandled special characters (like spaces) in your city name input. For example, if you type "New York", your URL becomes q=New York—spaces aren’t valid in URLs, so the API rejects the request immediately. Fix this by wrapping your city name with encodeURIComponent() to properly encode any non-URL-safe characters:

    const cityName = encodeURIComponent($("#city").val());
    

    This will convert spaces to %20 and other special characters to their URL-friendly equivalents, ensuring the API can parse your request correctly.

  • Secondary Issue: Incorrect Response Property Access
    Even if you fix the request, your current code will fail to render data because you’re accessing the wrong properties in the API response:

    • Temperature values (temp, feels_like) live inside the main object, not directly on the root data object
    • weather is an array of weather objects—you’ll need to grab a specific property from the first item (like main or description)

    Here’s the corrected .then() block to fix rendering:

    .then( (data) => {
      console.log(data);
      $("#name").text(data.name);
      $("#temp").text(data.main.temp);
      $("#feels").text(data.main.feels_like);
      $("#weather").text(data.weather[0].main);
    }, (error) => {
      console.log("bad request: ", error);
    })
    
  • Bonus: Add Input Validation
    To avoid empty requests (which also throw 400 errors), add a quick check before making the API call:

    function handleGetData(event){
      event.preventDefault();
      const cityName = encodeURIComponent($("#city").val().trim());
      
      // Block empty submissions
      if (!cityName) {
        alert("Please enter a valid city name!");
        return;
      }
      // Rest of your AJAX code...
    }
    

Full Corrected Code

function handleGetData(event){
  event.preventDefault();
  const cityName = encodeURIComponent($("#city").val().trim());
  
  if (!cityName) {
    alert("Please enter a valid city name!");
    return;
  }

  $.ajax({
    url: `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=99df413c60279878184277e08a2c6863`
  })
  .then( (data) => {
    console.log(data);
    $("#name").text(data.name);
    $("#temp").text(data.main.temp);
    $("#feels").text(data.main.feels_like);
    $("#weather").text(data.weather[0].main);
  }, (error) => {
    console.log("bad request: ", error);
  });

  console.log("It's working!");
}

$('form').on("submit", handleGetData);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:12:58