How to cause an Xmlhttprequest error?

Asked

Viewed 585 times

3

I would like to understand in which cases the readyState will be equal to 4 and the status will be different from 200 and the difference that for the event onerror:

xhr.onload = function (e) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error(xhr.statusText);
        }
    }
}
xhr.onerror = function (e) {
    console.error(xhr.statusText);
}

2 answers

3

According to the page of the MDN*:

A XHR request exists in one of the following states:

  • 0 - UNSENT - A client has been created. But the method open() hasn’t been called yet.

  • 1 - OPENED - The method open() was called.

  • 2 - HEADERS_RECEIVED - The method send() was called and headers and status are available.

  • 3 - LOADING - Downloading and responseText contains the partial data.

  • 4 - DONE - Operation completed.

That is, when the value is 0, the request of the XMLHttpRequest (AJAX) has not started yet and when it is 4 it is already over. The other states represent intermediate steps. Since your code is only interested in knowing the result when it is ready, you have the if (xhr.readyState === 4).

Already the status is the HTTP status. The most common are 200 (ok), 404 (page not found), 403 (access denied), 500 (internal error on the server), among others. In your case, the 200 indicates that it worked and anything else would be a mistake.


* - Adapted by me to fit the format of Sopt.

2


The .onerror will only be invoked if there is a network error, otherwise it will always enter the .onload and ignore the onerror.

Example:

Suppose I’m on the website http://meusite.com and I have a file index.html in the root directory.

If I try to call xhr.open("GET","index.html",true);:

  • Will enter the onload error-free, with xhr.status == 200, because found the file normally.

If I try to call xhr.open("GET","indexxxxx.html",true);:

  • Will enter the onload "mistakenly" (actually is not an error, but only a return from which the file was not found), with xhr.status == 404, because couldn’t find the file.

If I try to call xhr.open("GET","http://google.com",true);:

  • Will enter the onerror, because it is not allowed to call domain different from the current one and the request was not even sent.

The readyState are phases of communication with the server (from 0 to 4), while the status is interpreted by browser (200, 404 etc...)

  • that’s exactly what I wanted to know, perfect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.