【问题标题】:how to print a javascript function to a pug file with node and express如何使用 node 和 express 将 javascript 函数打印到 pug 文件
【发布时间】:2018-03-05 16:59:36
【问题描述】:

我使用 express 和 pug 文件创建了一个节点应用程序。 express 应用程序调用并侦听端口 3000 并呈现 pug 文件。我有一个从 api 获取信息的函数,我希望能够使用这些信息并使用 pug 文件打印它。

这是我的 app.js 文件

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

这是我想从中获取信息以在 pug 文件中使用的函数。

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

这是 pug 文件。

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

我似乎无法从 pug 文件中获取要显示的信息。

如果您想查看更多我的代码,请告诉我。

我知道这可能不是创建和运行我的应用程序的最佳方式,但我是 node、express 和 pug 的初学者,这只是我尝试自己学习一些代码。

【问题讨论】:

  • 你的意思是要在渲染页面中显示函数的输出?
  • 你从哪里得到weather 参数? app.js 你在哪里渲染这个 pug 文件?
  • 是的,Aron 没错,我对这一切有点陌生。
  • 我更新了问题中的代码

标签: javascript node.js express pug


【解决方案1】:

你会想做这样的事情:

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

【讨论】:

  • 你能澄清一下到底是什么不工作吗?您的getWeather 函数是否返回一个可以通过天气对象解析的承诺?您的 printWeather 函数是否返回消息字符串?
  • 如果我放置一个 console.log(message);在 printWeather 函数中,它会打印正确的信息
  • 抱歉不能帮你调试。如果您确保您的代码符合我上面评论中的要求,那么事情应该可以工作。
  • 感谢您的帮助 :-)
【解决方案2】:

render 接受第二个参数,该参数接受要传递给视图的数据:

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

那么你就可以在 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

【讨论】:

  • 这一切都很好,但没有从我想要的功能中打印信息
  • 那么你知道如何向 pug 发送数据,那么问题出在哪里?如果可能,发布指向您的代码仓库的链接。
  • 我想帮忙。你能说明你是如何从 express 发送数据到 pug 的吗?
  • Javascript 函数不会“打印”到哈巴狗。您在如何将数据传递给哈巴狗时遇到问题,就像我在上面发布的那样。我将更新我的回复,以说明它如何适用于您的情况。
  • 感谢您的帮助,没有成功,但我会继续努力
猜你喜欢
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2017-01-02
  • 2020-11-06
  • 2020-04-01
相关资源
最近更新 更多