skip to Main Content

My HTTP GET request works perfectly, returning body data and response headers. The exact same request with the extra paramter , { method: "HEAD" } as per the docs and response.header to console but it only returns the prototype of the headers not the response header. Server side I can see there was a sucessful HEAD request that was returned with a status 200.

async function getHead() {
    const url = document.getElementById('url').value;
    if(url.slice(0, 4) != 'http') {
        alert("URL must start with http or https!")
        document.getElementById("responseCode").innerHTML = "ERROR"
        document.getElementById("responseBody").innerHTML = ""
    };
    try {
        const response = await fetch(url, { method: "HEAD" });
        if (!response.ok) {
        throw new Error(`Response status: ${response.status}`);
    }

    console.log(response.headers.entries());
    document.getElementById("responseCode").innerHTML = response.status;
    document.getElementById("responseBody").innerHTML = JSON.stringify(json);
    } catch (error) {
        console.error(error.message);
        document.getElementById("responseBody").innerHTML = error.message;
    }
}

I’m expecting a response exactly the same as the GET fetch but without the body, but I’m just getting the prototype & constructor? Picture of the console:

enter image description here

Full HTML & JS here

2

Answers


  1. response.json() retuns the response body parsed as a JSON. Since a HEAD request doesn’t return a body, it’s not surprising that this parsing fails. This is the same error you’d get from trying to parse an empty string (e.g., JSON.parse('')).

    Login or Signup to reply.
  2. The snippet below shows how to properly get your headers.

    See Headers documentation for more details.

    const MyURL = ('https://stackoverflow.com');
    const MyFetch = fetch(MyURL, {method: 'HEAD'});
    
    MyFetch.then
    (
      Response =>
      {
        const MyHeaders = Response.headers;
        
        for ( const HeaderPair of MyHeaders )
        {
          const [ Header, Value ] = HeaderPair;
          
          console.log(`${Header} = ${Value}`);
        }
      },
      Issue =>
      {
        console.log(Issue.message);
      }
    );

    IMPORTANT: This snippet does not work as the fetch always fails. But it’s better to edit the code, so I used it. It should work just fine in your script though.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search