我正在为Chrome开发一个Web Scraper扩展程序,我必须跨域访问一些信息。我将请求模式设置为CORS,但仍然无法访问“ Content-Length”:即使不是,它也会返回null。 通过谷歌搜索和阅读MDN的网站,我读到here,表明CORS请求中允许使用“内容长度”,但至少在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();