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
Aggregating the comments, you should make the following changes:
URL.searchParams
getWeather()
in submit event listenerThe
apiURL
variable is moved inside the event listener, so it takes the current value of the#search-bar
input when the form is submitted.Call
getWeather
function when the form is submitted.Use try-catch to handle any potential errors during the fetch operation.