如何使用 fetch() 从请求中获取响应的内容长度

新手上路,请多包涵

返回时出现错误 response.json() 当我使用空响应主体执行请求时,所以我试图在主体为空时返回一个空对象。我想要的方法是检查响应的 Content-Length 标头,然而,不知何故 response.headers.get('Content-Length') 以某种方式返回 null 。这是我的代码:

 function fetchJSON(url, options, state = null) {
    return fetch(url, Object.assign({}, options, {
            // TODO: Add options here that should be there for every API call
            // TODO: Add token if there is one
        }))
        .then(response => {
            // Pass the JSON formatted body to the next handler
            if (response.ok === true) {
                if (response.headers.get('Content-Length') === 0) return {};
                return response.json();
            }

            // If the response was not an 2xx code, throw the appropriate error
            if (response.status === 401) throw new AuthorizationError("You are not authorized to perform this action");

            // If it is an error code that we did not expect, throw an regular error and hope that it gets noticed by
            // a developer
            throw new Error("Unexpected response: " + JSON.stringify(response));
        });
}

你能帮我找到响应的 Content-Length 或者帮我找到另一种方法吗?

原文由 jbakker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

服务器应在服务器端使用 Access-Control-Expose-Headers 公开标头:

 Access-Control-Expose-Headers: Content-Length

@sideshowbarker 评论 解释了为什么您可以在浏览器的网络面板中看到标头,但是当您这样做时收到 null response.headers.get("Content-Length")

仅仅因为您的浏览器收到标头并且您可以在 devtools 中看到标头并不意味着您的前端 JavaScript 代码可以看到它。如果来自跨源请求的响应没有 Access-Control-Expose-Headers: Content-Length 响应——如本答案所示——那么你的浏览器本身将阻止你的代码访问标头.对于跨源请求,如果 Access-Control-Expose-Headers 值包含特定标头的名称,您的浏览器只会将特定响应标头公开给前端 JavaScript 代码。

您可以通过将其复制/粘贴到控制台来查看它的工作情况:

 fetch("//stackoverflow.com").then(response => console.log(response.headers.get("content-length")))

请注意, Headers.get 的返回值将是字节字符串,因此您必须将其转换为数字才能在数字表达式中使用它:

 Number(response.headers.get("content-length")) > 0

原文由 Ori Drori 发布,翻译遵循 CC BY-SA 4.0 许可协议

我只是通过将 response.json() 放在 try/catch-block 中并捕获当我尝试解析空主体时发生的错误来解决我的问题。这不是理想的解决方案,但对我有用。

原文由 jbakker 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题