Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS not working on Chrome/Firefox and Apache

I'm trying to get an AJAX request working between my browser and an Apache server(residing in a different domain) using CORS.

At the server side, I've made the following changes in the httpd.conf section of the server as per the responses in "Header set Access-Control-Allow-Origin in .htaccess doesn't work":

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

My AJAX call is of the form:

        $.ajax({
            url        :'https://x.x.x.x/validateCustomerID',
            type       : 'POST',
            cache    : false,
            crossDomain: true,
            contentType: 'application/json',
            beforeSend: function(xhr){
                    xhr.setRequestHeader("Access-Control-Allow-Methods","POST");
                    xhr.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With");
                    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            },
            data       : {loginId : '12345'},
            success    : function(response){console.log("Success"+JSON.stringify(response))},
            error      : function(response){console.log("Error"+JSON.stringify(response))}
        });
    }

I've also tried commenting out the beforeSend() in order to avoid a preflight request but it wasn't successful either.

The error messages that I receive on Chrome and Firefox are:

  • In Chrome:

"XMLHttpRequest cannot load https://x.x.x.x/validateCustomerID. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403."

  • In Firefox:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://x.x.x.x/validateCustomerID. (Reason: CORS request failed)."

There are no response headers received from the server in my browser which I think are mandatory for CORS to work and also logs in the server shows no request reaching it from my browser.

I would really appreciate if someone here can help me resolve this issue as I'm stuck here for quite a few days now and have used almost all hit and trial methods to make this thing work.

like image 634
Yash Kapila Avatar asked Oct 16 '15 10:10

Yash Kapila


1 Answers

This is my setup in site.conf that works in production now with apache2

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "authorization, origin, user-token, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

for a future reference I strongly suggest to bookmark this site http://enable-cors.org/index.html

like image 163
maurycy Avatar answered Oct 13 '22 23:10

maurycy