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

229
Visualizações
cannot render an ejs page with variables from axios api call

I have seen the others questions about this topic, but my problem is slightly different: I have an axios call inside the .then of another axios call, and then I take values from the API that I called with axios and in another .then I render an ejs page, but the first time I execute, it tries to render the page before axios calling are completed, so variable to build the page are undefined, in particular it prints the error 'h1 is undefined' and h1 is the first variable in the ejs document after nameCapitalized which, as you can see from the code, is form the request and not from the axios api call; from the second time it works perfectly, when it works, it prints in order the console.log statements in .then, so the execution order is right, at least from the second execution. This get request is made after clicking a link in the browser.

Here the code:

app.get('/private_:city/', function(req, response) {
        const name = req.params.city;
        const nameCapitalised = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
        let lat;
        let lon;
        let country;
        let jsonObj;
        let h1;
        let w1;
        let t1;
        let uv1;
        let rp1;
        let ws1;
    
        axios.get(`http://api.openweathermap.org/geo/1.0/direct?q=${nameCapitalised}&limit=1&appid=${apiKeyOpenWeather}`)
            .then(res => {
                console.log('first');
                lat = res.data[0].lat;
                lon = res.data[0].lon;
                country = res.data[0].country;
                console.log(res.data[0]);
                axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=daily,minutely&units=metric&lang=it&appid=${apiKeyOpenWeather}`)
                    .then(res => {
                        console.log('second');
                        jsonObj = res.data;
                        h1 = new Date(jsonObj.hourly[0].dt * 1000).getHours();
                        w1 = jsonObj.hourly[0].weather[0].description;
                        t1 = jsonObj.hourly[0].temp;
                        uv1 = jsonObj.hourly[0].uvi;
                        rp1 = Math.trunc(jsonObj.hourly[0].pop * 100);
                        ws1 = jsonObj.hourly[0].wind_speed;
                    })
                    .then(res => {
                        console.log('third');
                        response.render('private.ejs', {
                            title: nameCapitalised,
                            t1: t1,
                            h1: h1,
                            w1: w1,
                            uv1: uv1,
                            rp1: rp1,
                            ws1: ws1,
                        });
                    });
            });
    });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try to use only thens...

app.get('/private_:city/', function(req, response) {
        const name = req.params.city;
        const nameCapitalised = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
        let lat;
        let lon;
        let country;
        let jsonObj;
        let h1;
        let w1;
        let t1;
        let uv1;
        let rp1;
        let ws1;
    
        axios.get(`http://api.openweathermap.org/geo/1.0/direct?q=${nameCapitalised}&limit=1&appid=${apiKeyOpenWeather}`)
            .then(async (res) => {
                console.log('first');
                lat = res.data[0].lat;
                lon = res.data[0].lon;
                country = res.data[0].country;
                console.log(res.data[0]);
                return await axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=daily,minutely&units=metric&lang=it&appid=${apiKeyOpenWeather}`)})
                    .then(res => {
                        console.log('second');
                        jsonObj = res.data;
                        h1 = new Date(jsonObj.hourly[0].dt * 1000).getHours();
                        w1 = jsonObj.hourly[0].weather[0].description;
                        t1 = jsonObj.hourly[0].temp;
                        uv1 = jsonObj.hourly[0].uvi;
                        rp1 = Math.trunc(jsonObj.hourly[0].pop * 100);
                        ws1 = jsonObj.hourly[0].wind_speed;
                    })
                    .then(res => {
                        console.log('third');
                        response.render('private.ejs', {
                            title: nameCapitalised,
                            t1: t1,
                            h1: h1,
                            w1: w1,
                            uv1: uv1,
                            rp1: rp1,
                            ws1: ws1,
                        });
                    });
            });
    });
about 4 years ago · Juan Pablo Isaza Relatório

0

I think you should try to change variables order in the ejs document in order to understand if it is a problem of 'h1'

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