Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用node和express将javascript函数打印到pug文件_Javascript_Node.js_Express_Pug - Fatal编程技术网

如何使用node和express将javascript函数打印到pug文件

如何使用node和express将javascript函数打印到pug文件,javascript,node.js,express,pug,Javascript,Node.js,Express,Pug,我已经使用express和一个pug文件创建了一个节点应用程序。express应用程序调用并侦听端口3000,并呈现pug文件。我有一个函数,它可以从api中提取信息,我希望能够使用这些信息,并使用pug文件将其打印出来 const printWeather = (weather) => { let message =`The weather in ${weather.location.city} is currently ${weather.current_observatio

我已经使用express和一个pug文件创建了一个节点应用程序。express应用程序调用并侦听端口3000,并呈现pug文件。我有一个函数,它可以从api中提取信息,我希望能够使用这些信息,并使用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);
            }
        });
doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 #{message}
这是我的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);
            }
        });
doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 #{message}
这是哈巴狗档案

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);
            }
        });
doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 #{message}
我似乎无法从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);
            }
        });
doctype html
html(lang="en")
  head
    title Weather App
  body
    h1 Weather App
    h2 #{message}
如果你想看到更多我的代码,请让我知道


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

你会想做一些类似的事情:

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
采用第二个参数,该参数接受要传递给视图的数据:

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}

您的意思是要在呈现页面中显示函数的输出吗?从哪里获取
weather
参数?在
app.js
中,你在哪里呈现这个帕格文件?是的,阿隆,是的,我对这一切都有点陌生。我在问题中更新了我的代码,这一切都很好,但没有打印我想要的函数的信息,所以你知道如何向帕格发送数据,那么问题出在哪里?如果可能的话,发布一个链接到你的代码回购。我想帮助你。您能说明如何将数据从express发送到pug吗?Javascript函数不会“打印”到pug。您在如何将数据传递给帕格方面遇到了问题,就像我在上面发布的一样。我会更新我的回复,以显示它如何适用于您的情况。谢谢您的帮助,它没有起作用,但我会继续尝试。您能澄清什么不起作用吗?您的
getWeather
函数是否返回与weather对象解析的承诺?您的
printWeather
函数是否返回消息字符串?如果我放置一个console.log(消息);在printWeather函数中,它会打印正确的信息抱歉,我无法帮助您调试。如果您确保您的代码符合我在上面的评论中的要求,那么应该可以工作。无论如何,感谢您的帮助:-)