javascript - 无法访问 Fetch API 中的标头“Content-Length”,Chrome 扩展程序中的 CORS 请求
问题描述
我正在为 Chrome 制作 Web Scraper 扩展,我必须跨域访问一些信息。我将请求模式设置为 CORS,但我仍然无法访问“内容长度”:即使不是,它也会返回 null。通过谷歌搜索和阅读 MDN 的网站,我在这里读到CORS 请求中允许使用“Content-Length”,但至少在 Google Chrome 中似乎并非如此。我 100% 确定标头是由服务器提供的:我检查了 Chrome 的 DevTools 网络选项卡,它显示了它。
只是为了说得很清楚,我不能在后端改变任何东西。
我可以做些什么来访问该标题吗?如果我对此无能为力,谁能解释一下为什么 Chrome CORS 请求中禁止 HTTP 标头“Content-Length”?
对于我的扩展,我像这样包装了 Fetch API:
/**
* Utility wrapper function for the 'fetch()' API, allows automatic retry upon
* any error occurring during the request. It will trigger a given callback or waits
* a specified amount of time before re-executing the function (4000 milliseconds
* by default) whenever 'fetch()' throws an exception or returns an error state.
* @param input 'fetch' API argument.
* @param init 'fetch' API argument.
* @param timeout Upon error, milliseconds to wait before retrying.
*/
const $fetch = async (input, init, onerror, timeout) => {
try {
const response = await window.fetch(input, init);
if (response.status >= 400) {
await new Promise(r => setTimeout(r, timeout));
if (onerror) {
return await onerror();
} else {
init.cache = 'no-cache';
return await $fetch(input, init, onerror, timeout);
}
} else {
return response;
}
} catch (e) {
await new Promise(r => setTimeout(r, timeout));
if (onerror) {
return await onerror();
} else {
init.cache = 'no-cache';
return await $fetch(input, init, onerror, timeout);
}
}
};
然后我调用包装好的 Fetch:
const response = await /* wrapped fetch */ $fetch(video.source, { // 'video.source' is a url for an external CDN.
mode: 'cors'
});
console.log(response.headers.get('Content-Length') || response.headers.get('content-length')); // null
// I'm consuming the response as a ReadableStream
const reader = response.body.getReader();
const pump = async () => {
const { done, value } = await reader.read();
if (!done) {
let blob = new Blob([value]);
// ...
await pump();
}
else {
// ...
}
};
await pump();
解决方案
推荐阅读
- javascript - String.matchAll 未定义
- c# - 序列不包含匹配元素 C# Web Api
- c# - 如何执行具有类型的方法
反对类型的迭代? - android - 数据绑定视图模型与 RxJava 2
- c# - Datetime2 到 Datetime 抛出错误,但没有传递任何日期时间
- scala - Spark Structured Streaming:导入图像文件以创建简单的 ML 应用程序
- python - 如何在不使用python中的for循环的情况下迭代一列的行以获得新列
- javascript - 检查用户是否与 Service Worker 重新联机
- c# - 如何使用 C# 静默打印 .docx
- rest - Spring Cloud Contract - 在 Groovy DSL 中转换响应