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')

No comments:

Post a Comment