我从我的 asp.net 表单中调用此函数,并在调用 ajax 时在 firebug 控制台上出现以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://anotherdomain/test.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
我已经做了替代方法,但仍然无法找到解决方案。
注意:我没有进行服务器端(API/URL)更改的服务器权限。
最佳答案
当您尝试访问其他域的资源时,通常会发生这种情况。
这是一项安全功能,可避免所有人自由访问该域的任何资源(例如,可以访问这些资源以在盗版域上拥有与您网站完全相同的副本)。
响应的 header ,即使是 200OK 也不允许其他来源(域、端口)访问资源。
如果您是两个域的所有者,则可以解决此问题:
.htaccess
要改变这一点,您可以在请求的域文件的.htaccess
中编写:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
如果您只想授予对一个域的访问权限,.htaccess
应如下所示:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.example'
</IfModule>
如果你把它设置到请求文件的响应头中,你将允许每个人访问资源:
Access-Control-Allow-Origin : *
或
Access-Control-Allow-Origin : http://www.my-domain.example
关于jquery - 缺少 CORS header 'Access-Control-Allow-Origin',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276220/