【发布时间】:2019-10-26 12:51:26
【问题描述】:
我正在从 AWS S3 获取静态资产(图像、pdf 等),并使用 service worker api 向客户端显示它们的下载进度。为此,我正在阅读响应中的“content-length”标头。在 Chrome Canary (77.0.3821.0) 中,这可以正常工作,但在 Firefox(版本 67.0)和 Chrome(版本 75.0.3770.80)中,响应中没有“content-length”标头。
This answer 在 SO 上有助于将 request.mode 设置为“cors”,这为我提供了一些初步成功,但到目前为止,这似乎只适用于 Chrome Canary。
function respondWithProgressMonitor(clientId, response) {
for (const key of response.headers.keys()) {
console.log(key); // returns only "content-type" and "last-modified" on chrome and firefox, but in Chrome Canary includes "content-length"
}
const contentLength = response.headers.get('content-length');
// ...
}
function fetchWithProgressMonitor(event) {
const request = new Request(event.request.clone(), {
mode: 'cors',
credentials: 'omit',
});
return fetch(request).then(response => respondWithProgressMonitor(event.clientId, response));
}
除非我做错了什么,否则我的 S3 存储桶 CORS 配置规则应该公开标头。
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
<ExposeHeader>Content-Length</ExposeHeader>
</CORSRule>
</CORSConfiguration>
我不确定为什么在 Canary 响应中公开了 content-length 标头,但在当前的 Chrome 版本或 Firefox 中却没有。我需要在请求中包含其他一些选项以在响应中取回“内容长度”标头吗?非常感谢您提供任何见解或线索。
【问题讨论】:
-
我认为这是因为直到一年前,Fetch 规范中的 CORS 要求还没有将 Content-Length 定义为“CORS-safelisted response-header name”fetch.spec.whatwg.org/#cors-safelisted-response-header-name .因此,由于它也被定义为“禁止的标头名称”fetch.spec.whatwg.org/#forbidden-header-name,因此要求浏览器永远不要将其暴露给前端 JavaScript 代码。这改变了github.com/whatwg/fetch/commit/3a896ef。另见github.com/whatwg/fetch/issues/622。但我猜浏览器直到现在还没有实现这个改变。
-
这些是一些非常棒的资源,这是否仅适用于
no-cors请求模式,还是应该在请求中添加cors模式允许我访问禁止域? -
适用于'cors'模式。将模式设置为“no-cors”将确保您的代码根本无法访问 any 响应标头——而不仅仅是禁止标头。 “no-cors”模式确保您的代码也根本无法访问响应正文。所以我之前评论中的所有内容都指的是“cors”模式,即跨域请求的正常模式。 (你基本上永远不想使用“no-cors”模式;该模式几乎只存在于使用服务工作者缓存资源的情况下。)
标签: javascript ajax amazon-s3 fetch service-worker