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

自古美人都是妖i 提交于 2020-06-08 07:19:39

问题


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


回答1:


You need to specify the method type of HEAD:

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

See updated fiddle



来源:https://stackoverflow.com/questions/47240975/how-to-fetch-using-fetch-api-only-headers-in-javascript-not-the-whole-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!