4

I am doing ajax post from jquery such that i will call two rest services belonging to different domain to perform my business logic. While doing this, I get a CORS issue and with google references,i added crossDomain: true to my ajax and now, this works completely fine only when there are no headers specified in the ajax (as below) and if i add headers, I get below error. Please advise.

$.ajax({
    method : 'post',
    dataType: 'json',
    crossDomain: true,
    headers : {
        "country" : "us",
    },
    url : 'myurl.do',
    async : true,
    beforeSend : function() {       
    },
    success : function(data) {
        console.log('success', data);               
    },
    error : function(request, status, error) {
        console.log('Error!', status, error, request);
    },
    complete : function() {
        console.log('Completed!!');
    }
});

Error if header is added in Ajax is as follows

"Error!" "error" "" Object { readyState: 0, getResponseHeader: .ajax/jqXHR.getResponseHeader(), getAllResponseHeaders: .ajax/jqXHR.getAllResponseHeaders(), setRequestHeader: .ajax/jqXHR.setRequestHeader(), overrideMimeType: .ajax/jqXHR.overrideMimeType(), statusCode: .ajax/jqXHR.statusCode(), abort: .ajax/jqXHR.abort(), state: .Deferred/promise.state(), always: .Deferred/promise.always(), then: .Deferred/promise.then(), 11 more… }

captainsac
  • 2,484
  • 3
  • 27
  • 48
Skanda
  • 835
  • 1
  • 15
  • 32

1 Answers1

2

Adding custom headers makes it a complex request that requires a Preflight OPTIONS request to receive CORS permission before the POST request is made.

Examine your browser's developer tools Net tab. You should see the OPTIONS request there.

You need to configure your server to respond to it with the Access-Control headers that you have set up for the URL you are actually wanting.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. Can you please point me to the good resource for configuring access-control in server. I am using apache-tomcat app server and i see lot of examples for server configuration to web server. – Skanda Jun 05 '15 at 07:16
  • Yes, I see OPTIONS in the request. So, by adding access-control configuration at server end, should I be able to send custom headers? – Skanda Jun 05 '15 at 07:23
  • Yes. You have to specify that your custom headers are allowed. http://stackoverflow.com/questions/21792759/confused-about-how-to-handle-cors-options-preflight-requests covers configuring Tomcat for OPTIONS requests. – Quentin Jun 05 '15 at 08:46