I have a website that is being accessed through multiple domain names.
Let's say the main hosted website is example.com and the forwarded domain names are example-x.com, example-y.com, example-z.com
When visitors access the forwarded domains, there are cross-domain requests made back to the main site, example.com.
Currently, I am encountering an error while making AJAX GET requests to JSON files:
The requested resource does not have the 'Access-Control-Allow-Origin' header. This means that the origin '' is not allowed access.
Even though the preflight OPTIONS request returns a status of 200 and the subsequent GET method also returns a status of 200.
OPTIONS;
https://i.sstatic.net/eNY9r.png
GET https://i.sstatic.net/A5D5f.png
I have added the following CORS headers in the host's .htaccess file;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And I'm using the following AJAX request for making GET calls;
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
After removing
setRequestHeader("Content-Type", "application/json; charset=UTF-8")
from the AJAX request, the preflight requirement was eliminated. However, the CORS error still persists. The screenshot below displays the request/response of the GET method. My assumption is that the correct .htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT https://i.sstatic.net/9TO1S.jpg