make a http head request in javascript

To make a HTTP HEAD request in JavaScript, you can use either the XMLHttpRequest object or the fetch API. Here are the code snippets for both approaches:

Using XMLHttpRequest:

index.tsx
var xhr = new XMLHttpRequest();
xhr.open('HEAD', '/your_url', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        console.log(xhr.getAllResponseHeaders());
    }
}
xhr.send(null);
213 chars
9 lines

Using fetch API:

index.tsx
fetch('/your_url', {
    method: 'HEAD'
})
.then(function(response) {
    console.log(response.headers);
});
109 chars
7 lines

Both approaches set the method to 'HEAD' and send the request to the specified URL. The response headers can be accessed in the callback function of XMLHttpRequest's onreadystatechange event or as a property of the Response object in the fetch API's then method.

gistlibby LogSnag