我正在托管一个网站,该网站有许多指向它的不同域名。
让我们调用托管网站 example.com 和 url 转发的域名 - example-x.com、example-y.com、example-z.com
当访问 url 转发的域时,跨域请求将返回到主机站点 example.com。
我目前正在向 json 文件发出 ajax GET 请求并收到以下错误;
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example-x.com' is therefore not allowed access.
即使预检 OPTIONS 返回状态 200 并且 GET 方法返回状态 200。
选项;
我在主机 htaccess 上设置了以下 CORs header ;
# <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>
然后我使用以下 ajax 请求调用 GET;
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();
编辑
从 ajax 请求中删除 setRequestHeader("Content-Type", "application/json; charset=UTF-8")
已删除预检要求,但是 CORs 错误仍然存在,屏幕截图下面显示了 GET 的请求/响应,我猜测 RequestURL 上没有设置正确的 htaccess header - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
最佳答案
您正在尝试通过 GET
请求检索 json。这应该是 simple request , 它不需要预检请求。
如果您查看来自 MDN 的预检请求的要求,您可以看到设置 Content-Type
而不是 application/x-www-form-urlencoded
, multipart/form-data
或 text/plain
将导致此预检请求。
如果您查看 the RFC 中的 content-type
,它是 “应该” “包含负载主体的消息”。但是您的获取请求没有有效负载。因此,从您的 ajax 调用中删除该 header 。
关于javascript - CORS - 不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46648020/