Skip to content
Advertisement

my xhr status return allways 200 however in my condition if it does not take it into account

I have a problem with my xhr. The xhr status returns always 200. However, in my condition if it does not take it into account.

In the condition it goes directly to the else while the xhr.status returns the response 200. In the condition I put an if the response was 200 then it was using this :

console.log ('hello');

However, he sends this back to me

console.log ('salut');

My code :

var XMLHttpRequest = require('node-http-xhr');
 

global.XMLHttpRequest = require('node-http-xhr');


var url = "https://www.google.com/";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);

xhr.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0");
xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
xhr.setRequestHeader("Connection", "keep-alive");
xhr.setRequestHeader("Upgrade-Insecure-Requests", "1");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
     console.log(xhr.status);
   }};


xhr.send();

if(xhr.status == 200){
  console.log('bonjour');
  }else{
    console.log('salut');
    
  }

Advertisement

Answer

You don’t have the response of your request right after the line xhr.send(). The result is available in the onreadystatechange function. So, you need to move your condition into this function.

Change from :

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
     console.log(xhr.status);
}};

xhr.send();

if(xhr.status == 200) {
  console.log('bonjour');
} else {
  console.log('salut');  
}

to :

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
     console.log(xhr.status);
   }

   // move the condition here
   if(xhr.status == 200) {
      console.log('bonjour');
   } else {
     console.log('salut');
   }
};

xhr.send();
Advertisement