XHR "error" event listener not working when URL is wrong. Confused as to why

Working through Colt Steele's JavaScript course, and learning about XHR. This snippet is supposed to throw an error when the URL isn't correct. If I type gibberish like /planetiuhnuoidhfugn/ it still works/I'm not seeing an error in Chrome DevTools. It'll throw the error if I change "swapi" to "swap" or "dev" to "co" as "swapi.co" no longer exists:
const firstReq = new XMLHttpRequest();
firstReq.addEventListener("load", function () {
console.log("IT WORKED!!!");
});
firstReq.addEventListener("error", () => {
console.log("ERROR!!!!!!");
});
firstReq.open("GET", "https://swapi.dev/api/planets/");
firstReq.send();
console.log("Request Sent!");
const firstReq = new XMLHttpRequest();
firstReq.addEventListener("load", function () {
console.log("IT WORKED!!!");
});
firstReq.addEventListener("error", () => {
console.log("ERROR!!!!!!");
});
firstReq.open("GET", "https://swapi.dev/api/planets/");
firstReq.send();
console.log("Request Sent!");
4 Replies
Joao
Joao15mo ago
That's probably because what constitutes an invalid URL is determined on whether the domain name can be resolved to an IP address or not. If you type gibberish at the route level (the planet), the domain has been correctly being resolved as swap.dev. The fact that there's no handler for the route https://swapi.dev/api/planetiuhnuoidhfugn/ does not mean that the URL is wrong, it just means that the resource does not exist. In contrast, if you provide a domain name that cannot be resolved to an IP address, for example "sawpi.dev" or "swapi.co" (assuming these are in fact not valid) then that's an error, and no connection can be made to any server.
ἔρως
ἔρως15mo ago
he's right, i just double-checked if you want to detect a bad path (404, 500, ...), then you can use the loadend event and check the status attribute of xhr instance the error event won't be triggered for those instances
Chimi
ChimiOP15mo ago
In the video, Colt typed gibberish at the route level and his threw the error, yet mine didn’t even though it was the exact same code. Hence my confusion 😂 I appreciate the explanation, I’ll experiment with it more
Joao
Joao15mo ago
The request may have failed for other reasons, for example if you try to open a request from a different domain you may get a content security policy error that blocks the request entirely.
Want results from more Discord servers?
Add your server