将解析的json数据传递到模板

时间:2019-07-03 20:09:39

标签: node.js ejs

从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:未定义数据     在app.get(/workspace/UdemyWebDev/c9Backup/weatherCall/app.js:42:30)”处,指向res.render回调中的{data:data}对象。 经过数小时的困惑之后,使用res.locals仍然是一个谜。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我发现的是,选择一个与天气对象绑定的任意局部变量名称(关键字),然后使用以下关键字:天气对产生已定义的值。然后将key.parameter.parameter.etc ...插入模板以显示数据。 EUREKA! ...但是后来我回到家,来到了我刚刚上过云的地方,没有肥皂。回到画板...

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>  

一切都很好。

相关问题