简体   繁体   中英

xmlHttpRequest status = 0

I have a website (wagtail CMS) running at AWS at domain:8000 and my API running at domain:8801

On my webpage I try to get some info from API by using JS (Access-Control-Allow-Origin header is set correctly at API, it's a django-based app)

Unfortunately the following code returns only xhr.status = 0 and empty responseText no matter what I try to access.

When I put domain:8000 at xhr.open('GET',' http://domain:8000 ',true) everything works just fine, I see my html code.

function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
if (xhr.status != 200) {
  alert( "ERR" ); --always ERR in browser
    } 
    else {
        alert( "SUCCESS" );
    }
}

On the API side I see all my requests, status=200 in server console.

You're supposed to use a callback function to catch the response from a request using the XMLHttpRequest object. Do something like this instead:

xhr.addEventListener('readystatechange', function() {
    if (xhr.status != 200) {
      alert( "ERR" ); --always ERR in browser
    } else {
      alert( "SUCCESS" );
    }
  }
});

Look here for docs and an examples on doing that.

You need to wait for xhr.readyState == 4 before xhr.status is at all valid (actually I think it's valid at 3, but lets keep consistent with 99.999% of code in the wild)

function load() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://domain:8801/api/', true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status != 200) {
                alert( "ERR" ); --always ERR in browser
            } 
            else {
                alert( "SUCCESS" );
            }
        }
    };
    xhr.send();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM