此处的新手程序员尝试使用api制作一个简单的应用程序。到目前为止,我正在使用开放式天气地图的api和google geocoder。我已经对其进行了设置,以便用户可以输入城市,州,国家或地区甚至大陆,并且它应该以温度和描述作为响应。没什么好看的。问题是,当用户输入拼写错误的城市或州/省时,我的应用程序崩溃了,服务器崩溃了。这甚至发生在像老挝这样的国家/地区-拼写正确,但仍然出现相同的错误。我正在使用ejs文件显示结果。这是一些代码:
{"cod":"404","message":"city not found"}
TypeError: /Users/jamesmolnar/Desktop/NewApps/weather/views/results.ejs:5
3| <h3>Here are the results:</h3>
4| <p>
5| <% data.weather.forEach(function(result) { %>
6| <%= console.log(data.weather) %>
7| <%= result.description %>
8| <% }) %>
Cannot read property 'forEach' of undefined
My app.js file:
// require("dotenv").config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
const request = require("request");
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
});
app.get("/results", (req, res) => {
let query = req.query.search;
let weatherApiKey = "0a79f1c8132aac82c5c086a570df5224";
let weatherUrl =
"https://api.openweathermap.org/data/2.5/weather?q=" +
query +
"&appid=" +
weatherApiKey;
request(weatherUrl, (err, response, body) => {
if (!err) {
let data = JSON.parse(body);
console.log(body);
res.render("results", { data: data });
} else {
console.log(err);
}
});
let location = req.query.search;
let geoCodeApiKey = "AIzaSyBrxDkJD5NFSQqKFbc5axWn0sGPg0bRYn8";
let geocodeMapUrl =
"https://maps.googleapis.com/maps/api/geocode/json?address=" +
location +
"&key=" +
geoCodeApiKey;
request(geocodeMapUrl, (err, response, body) => {
if (!err) {
let mapData = JSON.parse(body);
console.log(body);
res.render("results", { mapData: mapData });
} else {
console.log(err);
}
});
});
app.listen(PORT, () => {
console.log("Weather App is listening on PORT:", PORT);
});
my results.ejs file
<%- include ("./partials/header") %>
<h3>Here are the results:</h3>
<p>
<% data.weather.forEach(function(result) { %>
<%= console.log(data.weather) %>
<%= result.description %>
<% }) %>
<% let tempInFahrenheit = (data.main.temp * 9/5) - 459.67; %>
<%=Math.floor(tempInFahrenheit)%> degrees outside.
</p>
<div id="map"></div>
<a href="/">Back</a>
<%- include ("./partials/footer") %>
答案 0 :(得分:0)
由于您的模板无法在未定义的forEach
变量上生成result
语句,导致应用程序崩溃。
一个真正简单的解决方法是将该特定模板包装在if
条件内。
<%- include ("./partials/header") %>
<h3>Here are the results:</h3>
<p>
<% if (result && data) { %>
<% data.weather.forEach(function(result) { %>
<%= console.log(data.weather) %>
<%= result.description %>
<% }) %>
<% let tempInFahrenheit = (data.main.temp * 9/5) - 459.67; %>
<%=Math.floor(tempInFahrenheit)%> degrees outside.
<% } %>
</p>
<div id="map"></div>
<a href="/">Back</a>
<%- include ("./partials/footer") %>
如果您拼错城市名称,则应输入404。另外,输入的老挝也会抛出404,因为它是一个国家/地区名称。