Monday, October 23, 2017

Overcoming "No 'Access-Control-Allow-Origin' header is present on the requested resource." in jQuery

When calling a backend service via cross domain, if we do not set CORS header we will get above javascript error in browsers.
To overcome this issue in jQuery, we can set headers parameter.

eg:
$.ajax({
type : 'GET',
url : http://abc.com,
headers : {
'Access-Control-Allow-Origin' : '*'
},
success : function(data, textStatus) {
alert('success');
},
error : function(xhr, textStatus, errorThrown) {
alert('error');
}
});
At the same time, server too needs to allow cross domain requests to be served.

We can set request headers at server side..

Eg:
  request.setHeader('Access-Control-Allow-Origin', '*') 
  request.setHeader('Access-Control-Allow-Methods', 'GET')
  request.setHeader('Access-Control-Allow-Headers', 'x-prototype-version,x-requested-with')

1 comment:

  1. Yes, I agree that Hiring app developers may seem an easy task to handle at first sight, but in reality, it’s a multistep process with various pitfalls that may cost you a reputation if the final product is poorly-implemented.
    That's why I suggest hiring a top-rated freelance app developer on the emerging freelance marketplace Eiliana.com so that you get high-quality deliverables on time.

    ReplyDelete