I'm studying and building a weather journal app for a project using openweathermap.
When I write a zip code that doesn't belong to the country of my API, the console logs "cod:404 message:city not found", but I don't know how to display this to the user. I know that I need to write a conditional with an alert (wrong zip code!) before my postData code but I'm stuck here...
function action(e){
const postalCode = document.getElementById('zip').value;
const feelings = document.getElementById('feelings').value;
console.log(newDate);
getTemp(baseUrl,postalCode, apiKey)
.then(function (data){
if(/*Message error*/){
alert('Wrong zip code, try again!');
}
//Route
postData('http://localhost:8000/addData', { date: newDate, temp: data.main.temp, feel: feelings})
.then(function(){
//User Interface
updateUI()
})
})
}
As the response is an object containing cod
and message
, you can check if (data.cod === 404) {
Then show your alert.
Note that you need to return;
or put the postData
in the else
, otherwise it still would be executed after the alert shows
Problem with @Yehr59 's answer, is that the getTemp
probably won't throw an error, therefore it doesn't reach the .catch
function. So in the .then
you can perform the check I mentioned above in this answer.
You would have something like this:
getTemp(baseUrl,postalCode, apiKey)
.then(function (data){
if(String(data.cod) === '404'){
alert('Wrong zip code, try again!');
} else {
//Route
postData('http://localhost:8000/addData', { date: newDate, temp: data.main.temp, feel: feelings})
}
I also wrapped data.cod around String
, so it's always a string. We can't compare
"404" === 404 // false
Edit: Another way is to modify your getTemp
function so that it would throw
an error if the response code is 404, then you know once the .then is called, it's successful, and if the .catch is called, you'll handling an error