首页 > 解决方案 > 无法访问 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();

标签: javascriptgoogle-chromegoogle-chrome-extensioncorshttp-headers

解决方案


推荐阅读