天气API数据请求

时间:2019-02-20 13:10:41

标签: node.js rest axios ejs

我有这个ejs模板,可以输入城市的名称,然后将城市存储到数据库中,然后显示相关的天气结果。我创建了一个控制器,用于从该输入框发布城市信息。城市名称可以轻松存储并获得成功消息,但不会将该城市传递给天气API URL中的GET请求以显示相关的天气详细信息。

这是我的城市管理员:

const mongoose = require('mongoose');
const axios = require('axios');
const City = require('../models/city');

exports.addCity = (req, res, next) => {
    const city = new City({
        _id: new mongoose.Types.ObjectId(),
        cityName: req.body.cityName
    });
    city
        .save()
        .then(result => {
            console.log(result);
            res.status(201).json({
                message: "Created city successfully"
            });
        })

        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            });
        });
};


exports.getCity = (req, res, next) => {

    City.find({}).then(docs => {
            cities: docs.map(doc => {
                return {
                    city: doc.cityName
                }
            })

            let apiKey = '**************************';
            var city = cities;
            var url= `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
            axios(url)

            .then( (response) => {

                var cityData = response.data;

                var weather = {
                    city: city,
                    temperature: Math.round(cityData.main.temp),
                    description: cityData.weather[0].description,
                    icon: cityData.weather[0].icon
                }

                // var weather_data = { weather : weather };

                console.log('heyyyy', weather);

                res.render('index', {
                    weather: weather
                });
            })
            .catch( (error) => {
                console.log(error);
            })
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
})

}

这是ejs模板的代码段:

                     <article class="media">
                            <div class="media-left">
                                <figure class="image is-50x50">
                                    <img src="http://openweathermap.org/img/w/<%= weather.icon %>.png" alt="Image">
                                </figure>
                            </div>
                            <div class="media-content">
                                <div class="content">
                                    <p>
                                        <span class="title"><%= weather.city %></span>
                                        <br>
                                        <span class="subtitle"><%= weather.temperature %></span>
                                        <br> <%= weather.description %>
                                    </p>
                                </div>
                            </div>
                        </article>

每当我运行本地主机时,它只会将城市创建到数据库中,并在显示控制台中显示很多错误数据,最后两行显示:

data: { cod: '404', message: 'city not found' } } }
{ _id: 5c6d4e18d1ad342458c3df64, cityName: 'mumbai', __v: 0 }

请帮助找出问题所在。

1 个答案:

答案 0 :(得分:0)

您提供的getCity控制器看起来有些语法错误,但是我尽力使用它。主要变化是1.查找匹配文档的逻辑和2.使用Axios构造GET查询的方式

exports.getCity = (req, res, next) => {
  const cityName = req.query.cityName;

  City.find({})
    .then(docs => {

      // 1. Find matching city document
      const city = docs.find(doc => {
        return doc.cityName === cityName;
      });

      if (city) {
        const apiKey = "**********";
        const url = "https://api.openweathermap.org/data/2.5/weather";

        // 2. Axios GET query with params as object instead of interpolating inside url
        axios
          .get(url, {
            params: {
              q: city.cityName,
              appId: apiKey
            }
          })
          .then(response => {
            const cityData = response.data;

            const weather = {
              city: city,
              temperature: Math.round(cityData.main.temp),
              description: cityData.weather[0].description,
              icon: cityData.weather[0].icon
            };
            // Do something with weather
            console.log(weather);
          })
          .catch(err => {
            // Weather query failed
            console.log(err);
          });
      } else {
        // No city found matching cityName
      }
    })
    .catch(err => {
      // Database fetch failed
      console.log(err);
    });
};