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 Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
In our Fetch Response example (see Fetch Response live) we create a new Request object using the Request() constructor, passing it a JPG path. We then fetch this request using fetch() , extract a blob from the response using Response. blob , create an object URL out of it using URL.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With