【发布时间】:2019-11-14 13:35:46
【问题描述】:
解析来自 openweathermaps 的 JSON 数据。 Console.log 有效,但数据不会传递给 ejs 模板。我不断收到“数据未定义”错误。
看了很多视频教程,助教,但没有什么吸引人的地方。看起来很简单,只是忽略了一些小细节。或者也许它需要一个完整的重写。
app.use(function (req, res, next) {
let apiKey = "***************************";
let city = "Providence,US";
let url = `http://api.openweathermap.org/data/2.5/weather?
q=${city}&units=imperial&appid=${apiKey}`;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
let weather = JSON.parse(body);
let data = `temp ${weather.main.temp} wind ${weather.wind.speed}
from ${weather.wind.deg}`;
res.locals.weather = data;
console.log(data);
res.locals.error = null;
next();
} else {
res.locals.data = null;
res.locals.error = "There was an error current weather data.";
next();
}
});
});
app.get("/", (req, res) => {
res.render("index", {data: data});
});
app.listen(process.env.PORT || 3000, () => {
console.log("SERVER IS RUNNING!");
});
Console.log 产生解析的温度、风和方向。在浏览器中运行会产生错误“ReferenceError: data is not defined 在 app.get (/workspace/UdemyWebDev/c9Backup/weatherCall/app.js:42:30)",指向 res.render 回调中的 {data:data} 对象。 经过数小时的困惑,使用 res.locals 仍然是一个谜。任何帮助将不胜感激。
【问题讨论】:
-
这是因为
data的范围是中间件函数的本地范围,即在app.use(function (req, res, next) { /* */});内,因此它不适用于您的端点。 -
感谢您对 Shubham 的评论。我最终弄清楚的是如何使用正确的对象对,如以下代码所示,除了中间件的小改动: