简体   繁体   中英

CORS issue in Jquery Ajax Post

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… }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM