Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda