Here I have this sample fiddle, where I try to get only the content-type
header from a large image, using both XMLHttpRequest()
and fetch()
in Javascript. If you run the fiddle with Chrome's Developer Tools / Network tab (or similar tools in other browsers) open, you'll see that while the XMLHttpRequest()
method gets only the 600 B where the headers are located, the fetch()
method gets the whole 7.8 MB image, despite my code only needing the content-type
headers.
How can I get just those few bytes needed for the headers (instead of the whole content) using the Fetch APi's fetch()
?
Note: I am interested in this, because apparently, if I try to get the headers of all the links of a regular Google page, the XMLHttpRequest()
method logs me out and sometimes changes my language as well, while the fetch()
method does not. I assume this is because the former sends the credentials / cookies / etc., while the latter is more 'restrictive' by default...
You can't directly access the headers on the response to a fetch call – you have to iterate through after using the entries() method on the headers. Code sample (using react and looking for a query count) below: fetch(`/events? q=${query}&_page=${page}`) .
Working with HeadersYou can pass headers using the “headers” property. You can also use the headers constructor to better structure your code. But passing a JSON object to the “headers” property should work for most cases.
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.
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. createObjectURL , and display this in an <img> . Note that at the top of the fetch() block, we log the response headers to the console.
You need to specify the method type of HEAD
:
fetch(url, {method: 'HEAD'})
See updated fiddle
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