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

时间:2018-01-15 16:07:54

标签: javascript fetch-api

当我使用空响应主体执行请求时返回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或帮助我找到另一种方法?

4 个答案:

答案 0 :(得分:14)

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

Access-Control-Expose-Headers: Content-Length

@sideshowbarker comment解释了为什么您可以在浏览器的网络面板中看到标题,但在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")))

答案 1 :(得分:1)

我刚刚解决了我的问题,只需将response.json()放入try / catch-block并捕获我尝试解析空体时发生的错误。这不是理想的解决方案,但它对我有用。

答案 2 :(得分:-1)

你可以这样做:

 if (response.ok === true) {
        if (response.getResponseHeader("Content-Length") === 0) return {};
        return response.json();
 }

或者更容易这样:

 if (response.ok === true) {
        if (response.length === 0) return {};
        return response.json();
 }

你可以吗? :)

答案 3 :(得分:-2)

最后,您可以保持代码整洁,只需编写if (response.ok)