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

113
Visualizações
Pass data from POST route to template

I am trying to build simple weather app using node.js. I want to display weather information in the separate ejs file.

My code in post route looks like this:

app.post('/', (req, res) => {

   var address = req.body.address;

    location.getLocation(address, (error, results) => {
     if(error) {
         console.log(error);
     } else {
     fetchWeather.getWeather(results.latitude, results.longitude, (error, 
     weatherResults) => {
    if(error){
      console.log(error);
    } else {
      var temp = weatherResults.temperature;
      var appTemp = weatherResults.apparentTemperature;
      console.log(temp, appTemp);
    }
  });
 }
});
res.redirect('weatherinfo');
});

I am using request to get data in seperate file :

    var getWeather = (lat, lng, callback) => {

      request({
      url:`https://api.darksky.net/forecast/mycode/${lat},${lng}
      ?units=si`,
      json: true
       }, (error, response, body) => {
         if (!error && response.statusCode === 200) {
          callback(undefined, {

          temperature: body.currently.temperature,
          apparentTemperature: body.currently.apparentTemperature
       });
      } else {
     callback('Unable to fetch weather.');
   }
 });

};

How can I export temperature and apparentTemperature to my ejs file?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can pass the temperature data to the view as variables:

app.post('/', (req, res) => {

    var address = req.body.address;

    location.getLocation(address, (error, results) => {
        if(error) {
            console.log(error);
        } else {
            fetchWeather.getWeather(results.latitude, results.longitude, (error, weatherResults) => {
                if(error){
                    console.log(error);
                } else {
                    var temp = weatherResults.temperature;
                    var appTemp = weatherResults.apparentTemperature;


                    res.render('pages/yourFile.ejs, {
                        temp: temp,
                        appTemp: appTemp
                    });
                }
            });
        }
    });
});

and use them in your ejs file:

<p><%= temp %></p>
<p><%= appTemp %></p>
about 4 years ago · Santiago Trujillo Relatório

0

If you use something like express-session you can store your data in req.session object, and then use it in your file

If you don't need to have persistency across user session, you can store data in res.locals, which are recognized by most express view engines, for example EJS:

res.locals.temp = temp;
res.render('temp');

temp.ejs:

<% if (temp) { %>
  <h2><%= temp %></h2>
<% } %>
about 4 years ago · Santiago Trujillo 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