简体   繁体   中英

how to print a javascript function to a pug file with node and express

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.

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 });
    });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM