Calling OpenWeatherMap API is blocked due to CORS header ‘Access-Control-Allow-Origin’ missing

I’m not sure exactly what I’m doing wrong here. I’ve spent quite a while trying to fix this and no matter what I do I can’t seem to get it working.

My codepen is here:

I’m using getJSON to retrieve the JSON. Using console.log() it seems like the URL is formatted correctly, and when I paste it into the web browser it correctly displays the JSON. However, when trying to run my code on codepen, I get this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). And my getJSON function doesn’t run


Here’s an explanation of why this happens.

The tl;dr is to use a CORS proxy for your requests. Prepend to your API’s URL.

expirement with setting the cache to false on the request

1 Like

Hey, I recently ran into this problem and your solution worked perfectly fine, thank you so much. Before I saw your answer I was using a Chrome plugin that was working just fine but I had doubts whether that was a good solution. So I want to know if your solution is ok, considering I’m doing this task as an interview process and I’m sure they made me run into this problem intentionally to see how I’d handle it, that’s why I had concerns regarding the Chrome extension.

Why does this line do, why does it solve the issue?

The provided link already gives you the best explanation I can write. The short answer is that we’re not supposed to be writing apps that use API keys in the browser. They should only be used on the server.

This is definitely not a production-ready solution. For a real app, you want to properly configure your server’s security settings to allow your client application to communicate. An extension is not going to help you if you’re showing an app to an interviewer, you’ll need to make sure your code works for anyone.

Yeah that’s what I thought about the extension and that’s why I was digging for other solutions. I don’t have access to the server code, this is a front-end task only and to be honest I’m not entirely sure if it was intentional (my guess is that it was), considering what I just said, would you say that your solution is good enough? I’m guessing the CORS proxy will still work even after I host my solution online, correct?, if so, then I’d say the solution fixes the issue.

Yes, a CORS proxy should be just fine for your purpose. Ship it :ship:

1 Like

thank you !!!