CORS problem in JQuery Ajax Post

I am doing an ajax post from jquery so that I will call two rest services belonging to a different domain to execute my business logic. With this I get CORS issue and with google links, I added crossDomain: true to my ajax and now this works completely fine only if there are no headers in the ajax (as shown 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!!');
    }
});

      

The error if header is added in Ajax looks like this

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

+3


source to share


1 answer


Adding custom headers makes it a tricky request, requiring an OPTIONS pre-request to get CORS permission before the POST request is made.

Explore the Net tab of the developer's developer tab. You should see an OPTIONS request there.



You need to configure the server to respond to it with the Access-Control headers you've configured for the URL you actually want.

+2


source







All Articles