'OpenWeathermap country codes code problem "city not found"
I'm writing code for a weather journal app. The thing is when I pass to fetch method the URL of the site of openweathermap.com with the zip code and country code way it only accepts the country code as the US it never accepts another country. I tried so many but it never accepts any of those it only returns the data object of forecast to the US and for any other country it just shows the message city not found. Here is my code:
const generate = document.getElementById('generate').addEventListener('click', function(){
const zip = document.getElementById('zip').value;
const countryCode = document.getElementById('countryCode').value;
endPointData(zip,countryCode,apiKey);
})
const endPointData = async (zip,countryCode,apiKey) => {
const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);
try{
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
const postData = async (url='', data = {}) => {
const response = await fetch(url,{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
});
try{
const newData = await response.json();
return newData;
}catch(error){
console.log("error",error);
}
}
Solution 1:[1]
Working fine for me in other countries as well.
const apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const zipCode = "110007";
const countryCode = "IN";
const endPointData = async (zipCode, countryCode, apiKey) => {
const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},${countryCode}&appid=${apiKey}`;
const res = await fetch(URL);
try {
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
endPointData(zipCode, countryCode, apiKey);
Solution 2:[2]
console.log your URL variable. Maybe your country code is empty. The API falls back to US as default when country code is not specified. https://openweathermap.org/current#zip
Try it at postman first (https://www.postman.com/)!
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 | Suresh Mangs |
| Solution 2 | SuperSpamTube |
