Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No 'Access-Control-Allow-Origin' client side fix

I am trying to get free NFL data from an API by suredbits. Unfortunately, in their header, they have not added Access-Control-Allow-Origin, which creates a CORS issue. When I try and run code like this...

$.getJSON("http://api.suredbits.com/nfl/v0/stats/jones/julio", function(playerData) {
      alert(playerdata); 
}

I keep getting this error No 'Access-Control-Allow-Origin' header is present on the requested resource.

So basically, is their any way to fix their mistake through the client side?

like image 288
Ethernetz Avatar asked Oct 22 '25 15:10

Ethernetz


1 Answers

There is actually a way to fix it from client side: by changing the request URL to https://cors-anywhere.herokuapp.com/http://api.suredbits.com/nfl/v0/stats/jones/julio:

const proxyURL = "https://cors-anywhere.herokuapp.com/";
const requestURL = "http://api.suredbits.com/nfl/v0/stats/jones/julio";
$.getJSON(proxyURL + requestURL, function(playerData) {
  console.log(playerData);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Yeah, that’s not exactly fixing it from the client side—since what it’s actually doing is, causing the request to get made through https://cors-anywhere.herokuapp.com/, which is an open CORS proxy that just adds the Access-Control-Allow-Origin response header so that browsers will allow your frontend JavaScript code to access the response.

But as demonstrated in the code snippet in the answer, it definitely doesn’t require any changes to the server hosting the API endpoint you want to get data from. Instead all it requires a trivial change to your own frontend code.

Of course relying on a public open proxy like this is not the right solution in all cases. But at least it’s a good solution in the case where the API provider just hasn’t gotten around to CORS-enabling their API so that you could send requests to it directly and get responses you can use.

The How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API has a few more details.

like image 176
sideshowbarker Avatar answered Oct 25 '25 04:10

sideshowbarker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!