edward edward - 4 months ago 15
jQuery Question

Getting a error(Cross-Origin Request Blocked) when making an $.ajax call

I'm making a call to get some info however I keep getting this error

Cross-Origin Request Blocked: (Reason: CORS header 'Access-Control-Allow-Origin' missing)

$.ajax({
type: 'GET',
url: www.example.com/,
dataType:"json",
success: function(data) {
alert(data)
},
error: function() {
alert('error')
}
});


The stuff that is being returned is coming as json

any ideas?

Answer

I was able to solve my issue using the options below within my $.ajax call.

xhr.withCredentials = true; Access-Control-Allow-Credentials: true

Read the following to better understand this.

withCredentials

Standard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the XMLHttpRequest’s .withCredentials property to true:

xhr.withCredentials = true;

In order for this to work, the server must also enable credentials by setting the Access-Control-Allow-Credentials response header to “true”. See the server section for details.

Access-Control-Allow-Credentials: true

The .withCredentials property will include any cookies from the remote domain in the request, and it will also set any cookies from the remote domain. Note that these cookies still honor same-origin policies, so your JavaScript code can’t access the cookies from document.cookie or the response headers. They can only be controlled by the remote domain.

Hope this also helps you :)