jquery - 缺少 CORS header 'Access-Control-Allow-Ori

我从我的 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>

解决方案 2:正确设置标题

如果你把它设置到请求文件的响应头中,你将允许每个人访问资源:

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/

相关文章:

json - JSON 表示中的链接关系

json - Swift 4 可解码,直到解码时才知道 key

c# - 使用 Nancy 返回包含有效 Json 的字符串

json - 使用逗号拆分 NSString

javascript - 如何使用 Typeahead.js 0.10 一步一步/远程/预取/本地

json - bash 中的转义字符(对于 JSON)

json - 如何在 JSONPath 中按字符串过滤?

java - 字段上的 @JsonProperty 注释以及 getter/setter

javascript - 即使有循环引用,如何将 DOM 节点序列化为 JSON?

php - 从 PHP 中的 JSON POST 读取 HTTP 请求正文的问题