'JavaScript: How to Check if City Name exists in the OpenWeather API city list: Error Checking
In my weather app, I am trying to add the functionality that if the user enters a city name that is not in the OpenWeather API city-name list, then an error message pops up in an alert box instead of nothing happening. My only issue is with making the if statement. It is easy to check if a given string exists in an array or not however, I have never done a check to see if a string exists in an API list or not. I also don't want to download a huge file of all the city names and put them in my project because that would make it way too bulky. Does anyone know of an easier way to check this? I am using the OpenWeather API.
MY CURRENT CODE(City Section):
city.innerText = `${weather.name},${weather.sys.country}`;
//'weather.name' displays the actual City Name.```
pseudocode logic I think will work:
select city DOM element.
if (userInput is in CITYNAMES) {
city.innerText = cityName + cityCountry;
} else {
alert("City Not Found)
Solution 1:[1]
I think you should use an if-else statement like:
if(weather.cod===200){
city.innerText = `${weather.name},${weather.sys.country}`;
}
else{alert("City doesn't exist")}
if cod=200 then the city exists and hence can be loaded and if cod=404 then the city doesn't exist.
The image below shows up if you put an invalid cityname in an openweather url. [1]: https://i.stack.imgur.com/unLo6.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
