Weather app - help with Cross Origin Error

Hey everyone,

I just started the local weather project and I got this far:

https://codepen.io/virginiab/pen/JvRLwE

when I got this error:

“…has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://codepen.io’ is therefore not allowed access.”

Am I doing something wrong or is there a way to fix this?
Thanks in advance!

Cheers.

CORS is basically what allows you to talk to the API. the error says that the request, which is the API, does not allow requests that are not from the ‘allowed’ list. hence it mentions a header is not present. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

you can get around this by using JSONP, JSON with padding. the response is wrapped in a script tag and can then be parsed with a function call. since you are using jQuery, it has a JSONP method. attach ‘&callback=?’ to the end of the API request uri, and jQuery will make a JSONP request. but nowadays, it is discouraged to use such a solution now that CORS is available

though it’s weird that the FCC API has this issue. it should have headers

Thanks for your answer!

I think I will use a different API (one that has said headers) instead of the workaround in order to avoid a discouraged practice.

like i said, the FCC API should have headers already.

try the fetch api

let url = 'https://fcc-weather-api.glitch.me/api/current?lon=' + 39 + '&lat=' + 56; //lat and long placeholders

fetch(url)
  .then(response => {
    if (response.ok) {
      return response.json();
    }
  })
  .then(data => {
    // do stuff with data
    console.log(data);
})

that worked, it returns data properly.
There’s something wrong with my code and I don’t know what it is.

Edit: should clarify that it worked when i copy/pasted it over my entire code. Now that I tried to make it fit into what I’ve wrote it doesn’t work anymore and I’m getting the same error. So evidently, there’s something wrong with my code and not the api.

get rid of jquery and just use the fetch api. also make sure geolocation api is written properly