cferdinandi / atomic

A tiny, Promise-based vanilla JS Ajax/HTTP plugin with great browser support.
MIT License
540 stars 78 forks source link

onload cannot catch the network error #64

Closed allayli closed 6 years ago

allayli commented 6 years ago

https://github.com/cferdinandi/atomic/blob/c25dfe2f8c09722e7765aa6b375b67c506b8eaf1/src/js/atomic.js#L139

Use onreadystatechange instead of onload

Refer: https://stackoverflow.com/questions/28556398/how-to-catch-neterr-connection-refused

allayli commented 6 years ago
// Setup our listener to process compeleted requests
    request.onreadystatechange = function() {
        if (request.readyState == 4){
          // Process the response
          if (request.status >= 200 && request.status < 300) {
            // If successful
            resolve(parse(request));
          } else {
            // If failed
            reject({
              status: request.status,
              statusText: request.statusText
            });
          }
        }
cferdinandi commented 6 years ago

Is there a sample endpoint I can test to see what's happening now and test a fix?

allayli commented 6 years ago
let url="//0.0.0.0/1.png"; //Unreachable url
atomic(url).then(function (response) {
        console.log(response.data); // xhr.responseText
        console.log(response.xhr);  // full response
    })
    .catch(function (error) {
        console.log(error.status); // xhr.status
        console.log(error.statusText); // xhr.statusText
    });
cferdinandi commented 6 years ago

Thanks! Fixed: https://github.com/cferdinandi/atomic/pull/65