Anton
Anton

Reputation: 2368

How to get only response headers from XMLHttpRequest

Is it possible to get only response headers from XMLHttpRequest without downloading file data?

Upvotes: 4

Views: 16458

Answers (3)

Will Mayger
Will Mayger

Reputation: 11

Firstly, the answer from John fixes this issue but it got downvoted because it didn't have enough of an explanation.

So here is the fix with an explanation as well as an extra bit that you can add as well.

Client side solution is as follows (I am using the status code as the example):

function checkStatus(url) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest(); 
    request.open('HEAD', url, true)

    request.onreadystatechange = () => {
      if (request.readyState >= 2) {
        resolve(request.status)
        request.abort()
      }
    }

    request.onerror = (e) => {
      reject(e)
    }

    request.send()
  })
}

The reason why this works is for two reasons.

Firstly we are passing HEAD in as the method instead of GET this should be enough on its own, but if you want to do more, you can move onto the second reason.

The second reason this works is because of the readyState states.

0 = UNSENT
1 = OPENED
2 = HEADERS_RECEIVED
3 = LOADING
4 = DONE

At state 2 the headers are ready to be viewed. This means you can then return whatever you need and/or abort the rest of the request preventing any further data being downloaded.

Worth noting you can also do this with request.onprogress at stage 3.

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState and https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods for more details.

Upvotes: 1

John
John

Reputation: 13719

Using JavaScript (as specified in the question) simply use a head request via AJAX:

var xhr = new XMLHttpRequest();
var method = 'head';
var url = 'https://www.example.com/';
xhr.open(method,url,true);
xhr.send(null);

xhr.onreadystatechange = function()
{
 if (xhr.readyState === 4)
 {
  console.log(xhr.getAllResponseHeaders())
 }
}

Upvotes: 2

Stephen Ierodiaconou
Stephen Ierodiaconou

Reputation: 789

If the server you are making the request to supports the method, it sounds like what you want is to make an HTTP HEAD request. See the HTTP spec.

For example compare the output from curl -v -X GET https://github.com and curl -v -X HEAD https://github.com.

Also see HTTP HEAD Request in Javascript/Ajax?

Upvotes: 7

Related Questions