我有这个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>每当我运行我的localhost时,它只在数据库和显示控制台中创建城市,并返回大量错误数据,最后两行如下所示:
data: { cod: '404', message: 'city not found' } } }
{ _id: 5c6d4e18d1ad342458c3df64, cityName: 'mumbai', __v: 0 }请帮助我们解决这个问题。
发布于 2019-02-20 21:50:08
看起来您提供的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);
});
};https://stackoverflow.com/questions/54787156
复制相似问题