【问题标题】:passing parsed json data to template将解析的 json 数据传递给模板
【发布时间】: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 的评论。我最终弄清楚的是如何使用正确的对象对,如以下代码所示,除了中间件的小改动:

标签: node.js ejs


【解决方案1】:

我发现选择一个与天气对象相关联的任意局部变量名称(键),然后使用键:天气对产生定义的值。然后将key.parameter.parameter.etc...插入模板显示数据。尤里卡! ...但后来我回到家,去了我刚上的云 ide,没有肥皂。回到绘图板...

app.use(function(req, res, next) {
    request(url, function(err, response, body) {
    let weather = JSON.parse(body);
         console.log(weather);
        res.locals.key = weather;
        next();
    });
});

app.get("/", function(req, res){
    res.render("index", {key: weather});
    });

**Now, in the template:**

<ul class="key">
                <li>
                    <%= key.name %>
                </li>
                <li class="cur">
                    Temp: <%= key.main.temp %> f
                </li>
                <li class="cur">
                    Press: <%= key.main.pressure %> mb
                </li>
                <li class="cur">
                    RH: <%= key.main.humidity %> %
                </li>
                <li class="cur">
                    Speed: <%= key.wind.speed %> mph
                </li>
                <li class="cur">
                    Dir: <%= key.wind.deg %> deg
                </li>
                <li class="cur">
                    wx: <%= key.weather.description %> deg
                </li>
            </ul>  

一切都很好,花花公子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多