XMLHttpRequest CORS request failing, even with Access-Control-Allow-Origin header
Solution 1
The problem with the question is there is a fundamental misunderstanding of what CORS is. It is not for the origin server to specify which third-party domains a page can access through XMLHttpRequest requests, but rather it is the server on an external domain that specifies which domains can connect to it.
Solution 2
You can use *
to accept all origin but it will prevent using 'Access-Control-Allow-Credentials: true'
.
Take a look here for more examples - http://enable-cors.org/server_nginx.html
Comments
-
aherriot almost 2 years
I am having trouble making cross site ajax calls. Using nginx, I believe I have added the right headers in the server configuration, but it still does not work in my JS code or in the console. I wonder what I am doing wrong.
Here is what I type into the console the response is the familiar "No 'Access-Control-Allow-Origin' header is present" error:
$.get("//www.example.com"); Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…} XMLHttpRequest cannot load http://www.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dictionary.aherriot.com' is therefore not allowed access.
When I look at the response headers from my initial webpage load, I do see the following headers:
Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:X-Requested-With,Accept,Content-Type, Origin Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE Access-Control-Allow-Origin:*
and here is the nginx config file for the site:
server { listen 80; root /home/aherriot/sites/dictionary; index index.html index.htm; server_name dictionary.aherriot.com; location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin'; } }
I am stumped as to what I am missing. What else do I need to do to allow CORS? Thank you.