Reputation: 329
I am trying to handle an error when the input is not a valid URL. When I insert the input with a URL that does not exist, I am not getting the 404 status. I get the message:
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load
This is how I am trying to handle the error:
const imgURL = document.querySelectorAll('img');
imgURL.forEach(e => {
const url = e.getAttribute('src');
const http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
if (http.status === 404) {
console.log('You got an ERROR!')
};
});
What do I have to do to get the http.status === 404
?
Upvotes: 0
Views: 33
Reputation: 452
you can track the error like this and get the status from event parameter 'e' in onerror
callback function.
const imgURL = ["http://a.com", "https://b.com"];
imgURL.forEach(e => {
const url = e;
const http = new XMLHttpRequest();
http.open('GET', url);
http.onerror = (e) => {
console.log('DONE: ', e);
};
http.send();
});
Upvotes: 1