0

I have created a node app using express and a pug file. The express app called and listen on port 3000 and renders the pug file. I have a function which picks up information from an api and I would like to be able to use this information and print it using the pug file.

Here is my app.js file

'use strict';

const express = require('express') 
const app = express();
const pug = require('pug');

app.set('views', __dirname + '/views');
app.set('view engine', 'pug');


app.get('/', (req, res) => {
     res.render('index');
});

app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((err, req, res, next) => {
  res.locals.error = err;
  res.status(err.status);
 res.render('error');
});

app.listen(3000, () => {
    console.log('The application is running on localhost:3000!')
});

Here is the function I would like to get information from to be used in the pug file.

const printWeather = (weather) => {

    let message =`The weather in ${weather.location.city} is currently ${weather.current_observation.weather}`;
    message += ` Current temperature is ${weather.current_observation.temp_c}C`;
    message += ` It currently feels like ${weather.current_observation.feelslike_c}C`;
    message += ` The wind speed is currently ${weather.current_observation.wind_mph}mph`;
    message += ` The UV is currently ${weather.current_observation.UV}`;
    message += ` The humidity is currently ${weather.current_observation.relative_humidity}`;
    message += ` The wind direction is currently in the ${weather.current_observation.wind_dir}`;
    message += ` The pressure is currently ${weather.current_observation.pressure_mb}hPa`;
    message += ` The idibility is currently ${weather.current_observation.visibility_km}km`;
}

function get(query){
    const readableQuery = query.replace('_', ' ');
    try {
        const request = https.get(`https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json`, response => {
            if(response.statusCode === 200){
                let body = "";
                response.on('data', chunk => {
                    body += chunk;
                });
                response.on('end', () => {
                    try{
                        const weather = JSON.parse(body);
                        if (weather.location){
                            printWeather(weather);
                        } else {
                            const queryError = new Error(`The location "${readableQuery}" was not found.`);
                            printError(queryError);
                        }
                    } catch (error) {
                        printError(error);
                    }
                });

            } else {
                const statusCodeError = new Error(`There was an error getting the message for ${readableQuery}. (${http.STATUS_CODES[response.statusCode]})`);
                printError(statusCodeError);
            }
        });

Here is the pug file.

doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 #{message}

I can't seem to get the information to display from the pug file.

If you would like to see any more of my code please let me know.

I know this maybe isn't the best way to create and run my app but I am a beginner with node, express and pug and this is just me trying to learn some code on my own.

4
  • Do you mean you want to display the function's output in the rendered page? Commented Mar 5, 2018 at 17:06
  • Where are you getting the weather parameter from? Where in app.js are you rendering this pug file? Commented Mar 5, 2018 at 17:12
  • yes Aron that is right, I'm a bit new to all this. Commented Mar 5, 2018 at 17:14
  • I updated my code in the question Commented Mar 5, 2018 at 17:16

2 Answers 2

1

You're going to want to do something like:

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

  // this assumes that `getWeather` returns a promise or is an async function
  getWeather(req)
    .then(weather => {

      // make sure the `printWeather` function actually returns the message
      const message = printWeather(weather);
      res.render('index', { message });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Can you clarify what exactly isn't working? Does your getWeather function return a promise that resolves with the weather object? Does your printWeather function return a message string?
If I place a console.log(message); inside the printWeather function it prints the correct information
Sorry I can't help you debug. If you make sure that your code follows the requirements in my comment above things should work.
Thanks for your help anyway :-)
0

render takes a second parameter that accepts data to be passed to the view:

const get = (query, res, req) => {

  // your query code... not shown to save space

  // lets start from inside the try block where you parse the body
  const weather = JSON.parse(body);
  // now instead of calling printWeather(weather);
  // you need to take the json data from the api call
  // and pass this json to the view
  if (weather.location) {
    res.render('index', { weather: weather, error: null } /* passed to index.pug */)
  } else {
    res.render('index', { weather: null, error: `the location was not found.` } /* passed to index.pug */)
  }
}

app.get('/', function (req, res) {
  get(`enter_a_query_here`, req, res);
})

Then you can use this data in index.pug.

doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 Data: #{weather.current_observation.weather}
    p Error: #{error}

Using Template Engines

8 Comments

This all well and fine but doesn't print the information from the function that I want
So you know how to send data to pug, then what is the problem? Post a link to your code repo if possible.
I want to help. Can you show how you are sending data from express to pug?
Javascript functions are not 'printed' to pug. You are having trouble with how data is passed to pug, like i posted above. I will update my response to show how it applies to your situation.
Thank you for trying to help, It hasn't worked but I will keep trying
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.