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:
Full HTML & JS here
2
Answers
response.json()
retuns the response body parsed as a JSON. Since aHEAD
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('')
).The snippet below shows how to properly get your headers.
See Headers documentation for more details.
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.