5

我不明白为什么这个 CORS 请求无法返回数据。

我在后端使用 Catalyst MVC,Firefox 24.0 作为浏览器。jQuery 1.9.1。请注意以下事项:

  1. otherdomain.com 需要客户端证书。
  2. 直接点击资源会返回预期的数据。( https://otherdomain.com/resource/1 ) 返回正确的数据。

我有一个测试请求的简单页面:

<script type='text/javascript'>
                function get_data() {
                        console.log("running");
                        $.ajax({
                                url: "https://otherdomain.com/resource/1",
                                dataType: 'json',
                                type: 'GET',
                                xhrFields: {
                                        'withCredentials': true
                                },
                                crossDomain: true
                        }).success(function(data) {
                                console.log(data)
                                $('#output').html(data);
                        }).error(function(xhr, status, error) {
                                alert("error");
                                console.log(xhr);
                        });
                }

    $(document).ready(function() {
            get_data();
    });
    </script>

</script>

这是我的请求标头:

GET /resource/1 HTTP/1.1
Host: otherdomain.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: https://mydomain.com/test.html
Origin: https://mydomain.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

这是我的响应标题。(来自 firebug 控制台的视图源副本)我在催化剂调试输出中看到请求作为 200 OK 并发送了内容。

HTTP/1.1 200 OK
Date: Mon, 28 Oct 2013 19:31:08 GMT
Server: HTTP::Server::PSGI
Vary: Content-Type
Content-Length: 653
Content-Type: application/json
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 1800
X-Catalyst: 5.90030
Via: 1.1 otherdomain.com

并且错误是从 ajax 调用中引发的:

readyState: 0
responseText: ""
status: 0
statusText: "error"

firebug 将请求事件中的响应正文显示为空,尽管它是 200 OK。

我认为使用“withCredentials”时需要飞行前请求,但我没有看到通过萤火虫发送的选项。

另外,我看不到Access-Control-Request-Header我的请求没有添加任何内容,因此我没有Access-Control-Allow-Headers从服务器返回任何内容。

现在,Catalyst 的前端是 Apache2,我在虚拟主机中使用 proxypass 将请求发送到 localhost:8080 上的 Catalyst。我不确定这是否有任何影响,但我认为这可能很重要。不过,它应该对浏览器是透明的。

谢谢你的帮助!

4

2 回答 2

16
  1. GET requests are not preflighted. See Here
  2. When responding to a credentialed request, server must specify a domain, and cannot use wild carding. (must not be Access-Control-Allow-Origin: *). See Here
于 2013-10-28T23:49:26.623 回答
0

我有一个类似的问题,在 Chrome 中一切正常,但是对于 Firefox 中的所有跨域请求(以及 IE 的类似问题),我得到 405。我尝试添加 xhrFields 和 crossDomain 标志。我也在使用 beforeSend 来实际执行xhr.withCredentials = true. 我确保我在服务后端有主机名匹配。我使用 Access-Control-Allow-Credentials 标头。

可能会有所不同的一件事......我只在存在 Origin 标头时发送这些标头,因为如果我没有获得 Origin,我对 Access-Control-Allow-Origin 的唯一响应可能是*因为我不知道是什么起源是。

于 2016-11-18T18:42:57.293 回答