【发布时间】: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