Estoy escribiendo código para una aplicación de diario meteorológico. La cuestión es que cuando paso al método de obtención de la URL del sitio de openweathermap.com con el código postal y el código de país, solo acepta el código de país, ya que EE. UU. Nunca acepta otro país. Intenté muchos pero nunca acepta ninguno de ellos, solo devuelve el objeto de datos de pronóstico a los EE. UU. Y para cualquier otro país, solo muestra el mensaje ciudad no encontrada . Aquí está mi código:
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); } }Trabajando bien para mí en otros países también.
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);console.log su variable de URL. Tal vez el código de su país esté vacío. La API recurre a EE. UU. de forma predeterminada cuando no se especifica el código de país. https://openweathermap.org/current#zip
¡Pruébelo primero en el cartero ( https://www.postman.com/ )!