EJS无法读取未定义的属性,我该如何解决?

时间:2018-04-30 15:18:43

标签: node.js express ejs

我的网站从现在到昨晚都已经破了,尽管我没有做任何改变。我正在建立一个抓住天气数据的网站。它直接基于中篇文章:https://codeburst.io/build-a-weather-website-in-30-minutes-with-node-js-express-openweather-a317f904897b

这是服务器js内容......

app.post('/', function (req, res) {
  let city = req.body.city;
  let country = req.body.country;
  let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}${
    country.length > 0 ? "," + country : ""
  }&units=imperial&appid=${api}`
  request(url, function(err, response, body){
    if (err) {
      res.render('index',
      {weather: null, error: "Please Enter Valid Location"});
    }
    else {
      let weather = JSON.parse(body)
      if (weather.main == undefined) {
        res.render('index',
        {weather: null, error: "Please Enter  Valid Location"});
      }
      else {
        let content = {
          temp: weather.main.temp,
          city: weather.name,
          condition: weather.weather[0].description,
          icon: "svgs/" + weather.weather[0].icon + ".svg"
        }
        res.render('index', {weather: content, error: null});
      }
    }
  })
});

这里是相应的EJS模板......

<% if (locals.weather !== null){ %>
   <p><%= locals.weather.city %></p>
   <p><%= locals.weather.condition %></p>
<% } %>

<% if(error !== null){ %>
  <p><%= error %></p>
<% } %>

它在昨晚工作,但现在它说&#34;无法阅读财产&#39; city&#39;未定义&#34;。

0 个答案:

没有答案