跨域请求到AWS S3的AJAX请求有时会导致CORS错误 [英] Cross-origin requests AJAX requests to AWS S3 sometimes result in CORS error
问题描述
我需要从S3中检索一些可公开访问的文件。
I need to get retrieve some publicly accessible files from S3.
这是我的S3 CORS配置:
That's my S3 CORS configuration:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
这是我的JS代码:
const response = await fetch(url, {
mode: 'cors',
});
const blob = await response.blob();
它有效,但并非总是如此。有时控制台中出现以下错误:
It works, but not always. Sometimes I have the following error in the console:
在' https://my-bycketuel/file.jpg '来自来源' https://my.host 已被CORS政策阻止:所请求的资源上没有 Access-Control-Allow-Origin标头。
Access to XMLHttpRequest at 'https://my-bycketuel/file.jpg' from origin 'https://my.host' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
但是在我重新加载页面(有时几次,有时只是一次)之后,错误消失了,我能够读取响应对象。
But after I reload the page (sometimes several times, sometimes just once) then the error is gone and I'm able to read the response object.
推荐答案
在这里进行操作。
我一直在查看Chrome开发工具中的成功请求和失败请求。我发现不成功的请求的状态码为: 200 OK(来自磁盘缓存)
,成功的请求的状态码为: 200 OK
I was looking at successful and unsuccessful requests in Chrome dev tools. I found that unsuccessful requests have Status code of: 200 OK (from disk cache)
when successful requests have Status code of: 200 OK
当我使用 cache禁用缓存:'no-cache'
时,问题就消失了。 / p>
When I disable caching using cache: 'no-cache'
then the problem is gone.
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
Origin: window.location.origin,
},
});
我仍然不明白为什么缓存的请求会遇到CORS问题,但至少我发现了解决方案-或更确切地说,一种解决方法。
I still don't understand why would cached request suffer from CORS issues, but at least I found a solution - or rather a workaround.
//编辑:
我发现自己并不孤单:已缓存的非CORS响应与新的CORS请求冲突
I found I'm not alone: Cached non CORS response conflicts with new CORS request
这篇关于跨域请求到AWS S3的AJAX请求有时会导致CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!