Skip to content

Instantly share code, notes, and snippets.

@deanrad
Last active April 9, 2021 09:26
Show Gist options
  • Save deanrad/d7bec0d437bb76bf5f43d1b0fd01799a to your computer and use it in GitHub Desktop.
Save deanrad/d7bec0d437bb76bf5f43d1b0fd01799a to your computer and use it in GitHub Desktop.
Using CORS-Anywhere via AJAX
/*
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&param1=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)
})
@VitoZM
Copy link

VitoZM commented Feb 19, 2021

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