skip to Main Content

I am attempting to create a weather app as a way to learn how to code. I have designed the app myself and followed a tutorial for the JavaScript, but I encountered a 400 error when using the OpenWeather API. Here is my code:

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>';
const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${searchbar.value}&units=metric&appid=${API_KEY}`;

document.querySelector('form').addEventListener('submit', (e) => {
  e.preventDefault();
 
  fetch(apiURL);
});

async function getWeather() { 
  const response = await fetch(apiURl);
  const data = await response.json();
  console.log(data);
}

What can I do to resolve the 400 error?

2

Answers


  1. Aggregating the comments, you should make the following changes:

    • re-evaluate the url everytime
    • use URL.searchParams
    • call getWeather() in submit event listener
    document.querySelector('form').addEventListener('submit', (e) => {
      e.preventDefault();
      getWeather();
    });
    
    async function getWeather() { 
      const apiURL = new URL("https://api.openweathermap.org/data/2.5/weather");
      apiURL.searchParams.set("q",searchbar.value);
      apiURL.searchParams.set("units","metric");
      apiURL.searchParams.set("appid",API_KEY);
      const response = await fetch(apiURL.toString());
      const data = await response.json();
      console.log(data);
    }
    
    Login or Signup to reply.
    1. The apiURL variable is moved inside the event listener, so it takes the current value of the #search-bar input when the form is submitted.

    2. Call getWeather function when the form is submitted.

    3. Use try-catch to handle any potential errors during the fetch operation.

    const searchbar = document.querySelector('#search-bar');
    const API_KEY = '<MY_API_KEY>';
    
    document.querySelector('form').addEventListener('submit', (e) => {
      e.preventDefault();
      
      const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${searchbar.value}&units=metric&appid=${API_KEY}`;
      
      getWeather(apiURL);
    });
    
    async function getWeather(apiURL) {
      try {
        const response = await fetch(apiURL);
        const data = await response.json();
        console.log(data);
        
      } catch (error) {
        console.error('Error fetching weather data:', error);
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search