Frederick Alcantara
Frederick Alcantara

Reputation: 37

XmlHttpRequest cannot load because it is blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

How do I create the origin header so that it works for all domains and browsers on all devices? Do I use some kind of callback? Where in my code do I place this?

var characters = [

"http://www.anapioficeandfire.com/api/characters/148",
"http://www.anapioficeandfire.com/api/characters/823",
"http://www.anapioficeandfire.com/api/characters/1052",
"http://www.anapioficeandfire.com/api/characters/1303",
"http://www.anapioficeandfire.com/api/characters/208",

];



$(".btn").click(clickButton);


function clickButton(e) {

e.preventDefault();

var i = $(this).attr("data-id");
console.log(characters[i]);

var data;

$.getJSON(characters[i], function(json) {
    data = json;

)};

Upvotes: 2

Views: 2729

Answers (1)

pjc89
pjc89

Reputation: 131

if you try invoking the API via HTTPS instead of HTTP it will work ( i tried right now ).

You're getting that error message, because the server is sending a redirect response ( HTTP/1.1 301 .. see the Location header ), without CORS headers. As you can see here:


 $ curl -v http://www.anapioficeandfire.com/api/characters/148
 *   Trying 104.27.137.190...
 * TCP_NODELAY set
 * Connected to www.anapioficeandfire.com (104.27.137.190) port 80 (#0)
 GET /api/characters/148 HTTP/1.1
 Host: www.anapioficeandfire.com
 User-Agent: curl/7.51.0
 Accept: */*
 
 HTTP/1.1 301 Moved Permanently
 Date: Sun, 21 May 2017 21:43:13 GMT
 Transfer-Encoding: chunked
 Connection: keep-alive
 Set-Cookie: __cfduid=d59cc58d4e217f93147944a7f5ae1b6231495402993; expires=Mon, 21-May-18 21:43:13 GMT; path=/; domain=.anapioficeandfire.com; HttpOnly
 Cache-Control: max-age=3600
 Expires: Sun, 21 May 2017 22:43:13 GMT
 Location: https://www.anapioficeandfire.com/api/characters/148
 Server: cloudflare-nginx
 CF-RAY: 362ab5c495ec42fe-MXP

The browser is then blocking the second request ( the one that would actually follow the redirect ) for that reason.

You can dig a little bit deeper into what CORS actually is here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Code Example

$.getJSON('https://www.anapioficeandfire.com/api/characters/148', function (json) {
   $('#api-response').text(JSON.stringify(json,null,4));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre id="api-response"></pre>

Let me recommend you to read a bit more about HTTP, Ajax and Javascript to get a better understanding of whats going on. This is pretty basic stuff.

Upvotes: 1

Related Questions