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

使用变量作为参数调用OpenWeather API时出现404错误求助

Fixing the 404 Error When Using Dynamic City Input in Your OpenWeatherAPI App

Hey there! The issue you're hitting is a super common pitfall when working with DOM elements and API calls—you're using the input element itself instead of its actual user-typed value in your API URL. Let's break this down and fix it right away.

What's Causing the 404?

Right now, when you try to plug citySearch into your API URL, you're referencing the HTML input element object (not the text the user entered). When you concatenate this object into a string, it turns into [object HTMLInputElement], making your API call look like this:

http://api.openweathermap.org/data/2.5/weather?q=[object HTMLInputElement]&appid={API key}

Unsurprisingly, OpenWeatherAPI can't find a city with that weird name, hence the 404 error.

The Fix: Use the Input's value Property

You need to access the value property of the input element to grab the actual city name the user typed. Plus, it's smart to encode the city name with encodeURIComponent()—this handles spaces (like "New York") or special characters (like "São Paulo") that would break the URL format otherwise.

Here's the updated click event handler code:

button.addEventListener("click", function(){
    // Get the trimmed input text to avoid accidental whitespace issues
    const cityInput = citySearch.value.trim();
    
    // Stop here if the user didn't enter anything
    if (!cityInput) {
        document.getElementById('weatherResponse').textContent = "Please enter a city name first!";
        return;
    }

    // Build the API URL with the properly encoded city name
    const apiSearch = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(cityInput)}&appid={API Key}`;
    
    console.log("Fetching data...");
    getJSON(apiSearch).then(data => {
        // Clear old results before showing new ones
        const weatherDiv = document.getElementById('weatherResponse');
        weatherDiv.textContent = "";
        
        const cityName = data.name;
        const country = data.sys.country;
        const description = data.weather[0].description;
        weatherDiv.append(`The weather in ${cityName}, ${country} is ${description}.`);
    }).catch(error => {
        document.getElementById('weatherResponse').textContent = `Oops! Couldn't fetch weather data: ${error.message}`;
        console.error(error);
    });
})

Key Improvements Here:

  • citySearch.value.trim(): Grabs the user's input and removes extra spaces, so accidental whitespace doesn't mess up the API call.
  • Empty input check: Prevents useless API calls when the user clicks submit without typing anything.
  • encodeURIComponent(): Makes sure the city name is URL-friendly, even if it has spaces or special characters.
  • Clearing old responses: Wipes previous weather data so the div doesn't get cluttered with multiple results.
  • Restored error handling: The catch block now shows a user-friendly message instead of just logging to the console.

Quick Tweak to Your getJSON Function

Your current getJSON function returns errors instead of rejecting the promise, which means the .catch() in your click handler won't trigger properly. Fix that by modifying the catch block:

const getJSON = async (api) => {
    try {
        const response = await fetch(api);
        if(!response.ok) 
            throw new Error(`HTTP error! Status: ${response.status}`);
        const data = await response.json();
        return data;
    } catch(error) {
        // Reject the promise so .catch() can handle errors properly
        throw error;
    }
}

Now any errors (like 404s or network issues) will correctly trigger the .catch() in your click event.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:22:34