Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it?
Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it?
Easy, just use the HEAD method, instead of GET or POST:
function UrlExists(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(this.status != 404);
}
};
http.send();
}
This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload
, onerror
and ontimeout
rather than onreadystatechange
).
getAllResponseHeaders
or getResponseHeader("header-name")
on the this
object (the XHR object) to get the actual headers received, as @Lawley mentioned. –
Ortegal 404
only doesn't indicate that the URL exists. For example, it's perfectly valid to use 403
instead. –
Necker The more modern approach is to use the Fetch API which replaced XMLHttpRequest
.
e.g. (within an async
function)
const url = "https://example.com";
const response = await fetch(url, { method: "HEAD" });
console.log(`Got status: ${response.status}`);
An XMLHTTPRequest object should have
getAllResponseHeaders();
getResponseHeader("header-name")
defined on it
© 2022 - 2024 — McMap. All rights reserved.