Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch (using Fetch API) only headers in Javascript, not the whole content?

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...

like image 213
Yin Cognyto Avatar asked Nov 11 '17 17:11

Yin Cognyto


People also ask

How do I fetch all headers from fetch call response?

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}`) .

How do I use fetch API headers?

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.

How do you display data from API in JS using Fetch?

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.

Which method is used to fetch all the headers from response body?

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.


1 Answers

You need to specify the method type of HEAD:

fetch(url, {method: 'HEAD'})

See updated fiddle

like image 98
KevBot Avatar answered Oct 16 '22 20:10

KevBot