Last active
April 9, 2021 09:26
-
-
Save deanrad/d7bec0d437bb76bf5f43d1b0fd01799a to your computer and use it in GitHub Desktop.
Using CORS-Anywhere via AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
If you are attempting to call an AJAX API, via GET which responds: | |
No 'Access-Control-Allow-Origin' header is present on the requested resource. | |
You can modify the way you query it to go through a server which will add the header. | |
Basically, you add the URL you want (with query string parameters) at the end of | |
'https://cors-anywhere.herokuapp.com/' | |
, and ensure that your ajax call is done with some additional options as shown below | |
See CORS-Anywhere documentation here for more: | |
https://github.com/Rob--W/cors-anywhere/#documentation | |
Note: this 'fix' relies on the Heroku App https://cors-anywhere.herokuapp.com/ | |
being up and running! Your milage may vary. NOT for production use :) | |
*/ | |
var originalURL = "https://some-api-without-cors?api_key=foo¶m1=val1"; | |
var queryURL = "https://cors-anywhere.herokuapp.com/" + originalURL | |
$.ajax({ | |
url: queryURL, | |
method: "GET", | |
dataType: "json", | |
// this headers section is necessary for CORS-anywhere | |
headers: { | |
"x-requested-with": "xhr" | |
} | |
}).done(function(response) { | |
console.log('CORS anywhere response', response); | |
}).fail(function(jqXHR, textStatus) { | |
console.error(textStatus) | |
}) |
Thank You
THANK YOU!!!!!
thx dude!
I'm trying it with a POST request and I got a 403 forbidden error, does this method work for post request?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perfect!