Cross-Domain Chrome 中的问题可能 b/c 奇怪的 Dart HttpRequest 行为

Cross-Domain issue in Chrome possibly b/c of strange Dart HttpRequest behavior

我知道伙计们,有很多关于 Amazon S3 Buckets 和 CORS 的问题。但是请让我添加我的。

所以我正在 Dart 中编写应用程序,并且我正在对托管在 S3 上的资源执行 ajax 请求。我原本想获取资源的前 100 个字节,这就是为什么我想出了下面这段漂亮的代码:

   HttpRequest req = new HttpRequest();
   req.open('GET', item.get('upload').get('url'));
   req.setRequestHeader('Range', 'bytes=0-99');
   req.onReadyStateChange.where((e) => req.readyState == HttpRequest.DONE).first.then((e) {
      print(req.responseText);
   });
   req.send();

你可能从这个问题的标题中猜到了,这段代码不起作用,我得到了一个

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

这对我来说似乎很奇怪,因为我设置了一个 CORS 应该可以防止这个问题...

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedHeader>*</AllowedHeader>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
    </CORSRule>
</CORSConfiguration>

无论出于何种原因,这显然是行不通的。我在 Firefox 中加载了该应用程序,瞧,它正在运行。似乎 CORS 确实有效,问题是因为 ChromeDart.

我摆弄了一下,出于某些原因,你可能会打扰一下,这里已经很晚了,我想到了这个:

   HttpRequest req = new HttpRequest();
   req.open('GET', item.get('upload').get('url'));
   req.setRequestHeader('Range', '0-99');
   req.onReadyStateChange.where((e) => req.readyState == HttpRequest.DONE).first.then((e) {
      print(req.responseText);
   });
   req.send();

是的,我刚刚从我之前截取的代码中删除了 bytes=。你猜怎么着,突然我的 ajax 请求运行并打印全文。呜呜呜?!我可以添加损坏的 Range Header 并解决此安全问题吗?好吧,这正是刚刚发生的事情。当然,我得到的不仅仅是前 100 个字节,但至少我得到了一些东西。由于我无法解释为什么损坏的 Range header 使请求有效,我用其他一些随机字符串替换了 Range header 并且其中的 none 有效.

我知道,您的想法可能刚刚被打破了 - 我的也是!因此,我想总结一下我们刚刚发现的内容。

真的喜欢吗?我的意思是,我不知道这里发生了什么。 谁能至少向我解释一些事情? - 如果有人有想法或解决方案来解决我无法在 Chrome 中获取前 100 个字节的问题,我将终生感激。

提前致谢!

我终于设法修复了这个错误。

不,它既不是 Chrome 也不是 Dart 错误。它与某些缓存有关。解决方案是一个简单的脏字符串查询 hack:

   HttpRequest req = new HttpRequest();
   req.open('GET', '${item.get('upload').get('url')}?t=${new Random().nextInt(99999)}');
   req.setRequestHeader('Range', '0-99');
   req.onReadyStateChange.where((e) => req.readyState == HttpRequest.DONE).first.then((e) {
      print(req.responseText);
   });
   req.send();

在查询中加入随机数会导致缓存,不知道是亚马逊还是Chrome缓存,做正确的事情。