0

So I am trying to build a simple weather app using Open Weather API, this is my first attempt to build anything with an API. The API key should be valid however I keep receiving this error messing in chrome console when trying to enter a city name. My JavaScript is below the error message, I'm not sure if the issue is in the code or I am somehow linking the source wrong for the API key or base. Any advice would be much appreciated!

(index):1 Access to fetch at 'https://openweathermap.org/data/2.5/weatherweather?q=London&units=metric&APPID=' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

const api = {
  key: "", 
  base: "https://openweathermap.org/data/2.5/weather"
}

const searchbox = document.querySelector('.search-box'); 
searchbox.addEventListener('keypress', setQuery); 

function setQuery(evt) {
  if (evt.keyCode == 13) {
    getResults(searchbox.value); 
    console.log(searchbox.value); 
  }
}

function getResults (query) {
  fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
    .then(weather => {
      return weather.json(); 
    }).then(displayResults); 
}

function displayResults (weather) {
  console.log(weather); 
}

1 Answers1

0

This is a CORS error. Cross-Origin Resource Sharing is an HTTP-header-based mechanism that allows a server to indicate any other origins than its own from which a browser should permit loading of resources.

Now, coming back to your problem, one easy fix is to use a CORS proxy. You can use the following-

https://cors-anywhere.herokuapp.com/http://api.openweathermap.org...

Also, not sure if this would work, you can check if there is an option to permit IP addresses in your API settings. If so, then add localhost to that list.

Ajay Yadav
  • 151
  • 1
  • 2
  • 11