Recently, I encountered a problem with my Spring MVC API backend where CORS was correctly configured. However, when attempting to make an Ajax call, Chrome threw the following error:
XMLHttpRequest cannot load 172.20.16.45:8082/cuponza. The request was redirected to '172.20.16.45:8082/cuponza/', which is disallowed for cross-origin requests that require preflight.
Below is the snippet of my JavaScript code:
$scope.sendRegistrationForm = function(){
var config = {headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods' : 'GET,OPTIONS',
'Access-Control-Allow-Headers' : 'X-Requested-With, Content-Type',
'Content-Type' : 'text/plain',
'Accept-Language' : 'en-US'
}
};
$http.get("172.20.16.45:8082/cuponza",config).
success(function(data){
alert(data);
}).
error(function(data,status){
alert(status);
})
}
I attempted running Chrome with the flag --disable-web-security, and it revealed that my server-side CorsFilter was functioning as expected. However, upon normal startup of Chrome, the filter on the server did not engage.
An update: removing the config object with the CORS headers resulted in a new error message:
XMLHttpRequest cannot load 172.20.16.45:8082/cuponza
. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '
localhost:8100' is therefore not allowed access
Furthermore, when inspecting the requests made by Chrome, the differences between starting normally and with the --disable-web-security mode were evident:
Starting Chrome normally: OPTIONS /cuponza HTTP/1.1 Host: 172.20.16.45:8082 Connection: keep-alive Access-Control-Request-Method: GET Origin: localhost:8100 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36 Access-Control-Request-Headers: access-control-allow-origin, accept-language, access-control-allow-headers, access-control-allow-methods Accept: / Referer: localhost:8100/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8
Starting Chrome in --disable-web-security mode: GET /cuponza HTTP/1.1 Host: 172.20.16.45:8082 Connection: keep-alive Access-Control-Allow-Origin: * Accept-Language: en-US Access-Control-Allow-Headers: X-Requested-With, Content-Type User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36 Access-Control-Allow-Methods: GET,OPTIONS Accept: / Referer: localhost:8100/ Accept-Encoding: gzip,deflate,sdch