How to get the content-length of the response from a request with fetch()

jbakker picture jbakker · Jan 15, 2018 · Viewed 14k times · Source

I was getting an error when returning response.json() when I would do a request with an empty response body, so I'm trying to just return an empty object when there is an empty body. The approach I was going for is to check the Content-Length header of the response, however, somehow response.headers.get('Content-Length') somehow returns null. Here is my code:

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));
        });
}

Could you maybe help me to find the Content-Length of the response or help me to find another approach?

Answer

Ori Drori picture Ori Drori · Jan 15, 2018

The server should expose the header using Access-Control-Expose-Headers on the server side:

Access-Control-Expose-Headers: Content-Length

@sideshowbarker comment explains why you can see the header in the network panel of the browser, but receive null when you do response.headers.get("Content-Length"):

Just because your browser receives the header and you can see the header in devtools doesn’t mean your frontend JavaScript code can see it. If the response from a cross-origin request doesn’t have an Access-Control-Expose-Headers: Content-Length response — as indicated in this answer — then it’s your browser itself that will block your code from being able to access the header. For a cross-origin request, your browser will only expose a particular response header to your frontend JavaScript code if the Access-Control-Expose-Headers value contains the name of that particular header.

You can see it working by copy/pasting this to the console:

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