Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
How do I get the users input to fetch the api url?
//OpenWeather Info
const weatherKey = '*********';
const weatherURL = 'https://api.openweathermap.org/data/2.5/weather'

//Page Elements
const input = document.querySelector("#input").value;
const button = document.querySelector('#submit');

//Fetch
const getWeather = async () => {
    try {
        const apiURL = weatherURL+ "?&q=" + input + "&APPID=" + weatherKey;
        console.log(apiURL);
        const response = await fetch(apiURL);
        if (response.ok) {
            const jsonResponse = await response.json();
            console.log(jsonResponse);
            return jsonResponse;
        } else {
            console.log("request failed!");
        }
    } catch (error) {
        console.log(error);
    }
**}**

const renderWeather = (data) => {
    document.querySelector("#weather-degrees").innerHTML = data.main.temp;
}

const executeSearch = () => {
    getWeather().then(data => renderWeather(data));
}

button.addEventListener('click', executeSearch());

I can't get the value of input when I type in the textbox and it won't fetch the apiURL. Before I even type in anything the console gives me this. Any help? console logs

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your input is set once beforehand. Instead, do something like:

const input = document.querySelector("#input");
// ...
const apiURL = weatherURL+ "?&q=" + input.value + "&APPID=" + weatherKey;
// or using a template literal
const apiURL = `${weatherURL}?&q=${input.value}&APPID=${weatherKey}`;

Mind that you should also URL encode the input.

Since input is only set once now, it's set to an empty string. You can directly visit the API url, i.e. https://api.openweathermap.org/data/2.5/weather?APPID=82510feaa0c1d3a300a7a754ff134404&q= and notice that it doesn't work. If you replace q= with a proper value, e.g. q=London, it will work fine.

Mind that the API will also return a 400 error (but with a different error message) if you pass it an invalid city. Read the error from the reponse body and properly display an error to the user about invalid input.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda