![](/img/trans.png)
[英]How to get the content-length of the response from a request with fetch()
[英]"Content-Length" header not included in response from service worker fetch
我正在从 AWS S3 获取静态资产(图像、pdf 等),并使用 service worker api 向客户端显示它们的下载进度。 为此,我正在阅读响应中的“内容长度”标头。 在 Chrome Canary (77.0.3821.0) 中,这可以正常工作,但在 Firefox(67.0 版)和 Chrome(75.0.3770.80 版)中,响应中没有“内容长度”标头。
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 中没有公开。 我的请求中是否还需要包含其他一些选项以在响应中取回“内容长度”标头? 非常感谢任何要遵循的见解或线索。
不是答案而是一种解决方法......将内容大小放在另一个标题中。 为标头名称创建类似 'x-content-length-visible' 的内容,这可能不是 serviceworker 保护的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.