CORS 请求与 Safari 一起工作

CORS request working with Safari?

本文关键字:一起 工作 Safari 请求 CORS      更新时间:2023-09-26

我理解为什么以下代码片段在Firefox和Chrome中不起作用:我们正在向另一个域发出AJAX请求。

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.perdu.com", true);
xhr.addEventListener("load", function() { console.debug(xhr.responseText); }, false);
xhr.send(null);

但是为什么 Safari 会输出这个呢?这是页面的实际内容。我有 Safari 7.1。

<html><head><title>Vous Etes Perdu ?</title></head><body><h1>Perdu sur l'Internet ?</h1><h2>Pas de panique, on va vous aider</h2><strong><pre>    * <----- vous &ecirc;tes ici</pre></strong></body></html>

更新

事实证明,从服务器或文件系统加载时,Safari的行为有所不同。

下面的原始答案使用file:///方案测试 CORS 功能。Safari允许用户绕过该方案的CORS。

正如乔纳森·克劳(Jonathan Crowe)在localhost上指出的那样,因此使用http://方案,Safari会阻止响应,就像Firefox和Chrome一样。

所以这个没有错误。至于文件系统上的行为,我想我们可以称之为功能或便利(考虑快速本地测试)?

注意:此更新依赖于一个额外的简单测试,以从 HTTP 服务器提供以下 HTML 代码段。没有什么花哨的,Safari只是表现得像其他人一样。

原答案

我可以重现这个问题。这可能是 Safari 7.1 中的一个错误,这是我在临时结论中发现的。

  • 在 Safari 7.0.1 上不可重现(参见 Jonathan Crowe 的评论)。
  • 两个主要区别:
    • Safari 是唯一不设置 Origin 标头的浏览器。其他人将其设置为 null .
    • WebKit版本在Safari和Chrome中有所不同。
  • 苹果的跟踪系统上没有与CORS相关的错误报告。

此外,此版本的 Safari 允许在 XMLHttpRequest 对象上设置 Origin 标头(Chrome 不这样做):

xhr.setRequestHeader("Origin", null);

将标头设置为 null 以更接近其他浏览器不会更改结果:Safari 7.1 仍然允许响应通过请求者。

我无法确定这是 Safari 7.1 中的一个错误,但它现在似乎是它的行为。

以下是一些详细信息。

测试页和代码

<html>
  <script>
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://www.perdu.com", true);
    xhr.addEventListener("load", function() { console.debug(xhr.responseText); }, false);
    xhr.send(null);
  </script>
</html>

经过测试的版本

  • 野生动物园 7.1 (9537.85.10.17.1)
  • 火狐 33.1
  • 铬 38.0.2125.122

(全部在 Mac OS X 10.9.5 上)

火狐请求转储

GET / HTTP/1.1
Host: www.perdu.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:33.0) Gecko/20100101 Firefox/33.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: null
Connection: keep-alive

Chrome 请求转储

GET / HTTP/1.1
Host: www.perdu.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Origin: null
Accept: */*
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fr;q=0.6,ja;q=0.4,pt;q=0.2

野生动物园请求转储

GET / HTTP/1.1
Host: www.perdu.com
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10
Accept-Language: en-us
DNT: 1
Connection: keep-alive

注意

我目前正在使用 CORS 在一系列浏览器上测试 Web API 的边缘情况。如果一个错误得到确认,它应该不会有太大的问题---只要API安全性足够严重(因为CORS不能保护服务器)!

更新

我已经问过苹果他们是否可以在他们的反馈网站上确认。

您可能在"开发"菜单中启用了"禁用本地文件限制"选项。这将允许 CORS 请求通过。