How to cause an XMLHttpRequest error?

2

I would like to understand in which cases readyState will be equal to 4 and status will be different from 200 and the difference of that for 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);
}
    
asked by anonymous 24.08.2017 / 20:50

2 answers

1

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

Example:

Suppose I am in the http://meusite.com site and I have a index.html file in the root directory.

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

  • You will enter%% with without error , with onload , because found the file normally.

If I try to call xhr.status == 200 :

  • It will enter the% w / w with error "(actually not an error, but only a return that the file was not found), with xhr.open("GET","indexxxxx.html",true); , because did not find the file.

If I try to call onload :

  • Will enter xhr.status == 404 , as it is not allowed to call domain different from the current one and the request was not even sent.
The xhr.open("GET","http://google.com",true); are phases of communication with the server (from 0 to 4), while onerror is interpreted by the browser (200, 404 etc ...)

    
24.08.2017 / 22:13
2

According to the MDN page *:

  

An XHR request exists in one of the following states:

     
  • 0 - UNSENT - A customer was created. But the open() method has not been called yet.

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

  •   
  • 2 - HEADERS_RECEIVED - The send() method has been called and the headers and status are available.
  •   
  • 3 - LOADING - Downloading and responseText contains partial data.
  •   
  • 4 - DONE - Operation completed.
  •   

That is, when the value is 0, the request of 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 if (xhr.readyState === 4) .

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

* - Adapted by me to fit the SOpt format.     

24.08.2017 / 21:28