0

I'm a beginner programmer/coder, and I've started doing the Local Weather app thing. When trying to get a piece of data from the API I've been struck with these errors (tried .getJSON() first):

1."Access to Font at '...' has been blocked by CORS policy".

2."Bootstrap tooltips require Tether."

3 ".XMLHttpRequest cannot load '...' No 'Access-Control-Allow-Origin' header is present on the requested resource."

Then I tried a workaround, using .ajax() with jsonp, but then I got hit with these errors:

1."Access to Font at '...' has been blocked by CORS policy".

2.Refused to execute script from '...' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

Now I have no idea what to do. Also, I was wondering, why the Tether error came up in the first example, because an hour ago I was not getting this error there and I'm still not getting it in the second example (the one with jsonp).

The .getJSON() code: http://codepen.io/Kestvir/pen/Mmgzjz

The .ajax() code: http://codepen.io/Kestvir/pen/oWvMBb

KestVir
  • 300
  • 3
  • 14
  • If API doesn't support CORS or JSONP....you have to use a proxy on your server or third party service. Not all api's can be accessed using ajax – charlietfl Apr 12 '17 at 00:14

1 Answers1

0

Add required headers in your AJAX call.

There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

Reference: How can I add a custom HTTP header to ajax request with js or jQuery?

Community
  • 1
  • 1
Hamza Rashid
  • 1,329
  • 15
  • 22