简体   繁体   中英

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

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?

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")))

Note that the return value of Headers.get will be a bytestring, so you will have to cast it to a number to use it in a numerical expression:

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

I just solved my problem by just putting the response.json() in a try/catch-block and catching the error that occurs when I try to parse an empty body. This is not the ideal solution, but it works for me.

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

You can do it like this :

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

Or more easily like this :

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

Is it ok for you ? :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM