Unable to log response from XMLHttpRequest

Issue

I have created one XMLHttpRequest class wrapper for GET request. I am not able to console log the response i am getting. Is there something i am missing in the code ?

HttpWrapper.js

class HttpCall {
  static get(endpoint, headers = {}) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function () {
        //the request had been sent, the server had finished returning the response and the browser had finished downloading the response content
        if (4 === xhr.readyState) {
          if (200 <= xhr.status && 300 > xhr.status) {
            resolve(xhr.response);
          } else {
            reject(xhr.status);
          }
        }
      };

      if (headers) {
        Object.keys(headers).forEach(function (header) {
          xhr.setRequestHeader(header, headers[header]);
        });
      }

      xhr.open("GET", endpoint, true);

      xhr.send(null);
    });
  }
}

export default HttpCall;

index.js

import HttpCall from "./utils/HttpWrapper";
import { BASE_BACKEND_URL } from "./constants/Config";

HttpCall.get(
  BASE_BACKEND_URL + "?event_family=session&source_id=guru1",
  function (response) {
    console.log(response);
  }
);

Solution

It looks like you’re passing a callback to your method call instead of using the promise you returned. Your call should be formed more like:

HttpCall.get(
  BASE_BACKEND_URL + "?event_family=session&source_id=guru1")
.then((response) => {
    // handle resolve
    console.log(response);
}).catch((error) => {
    // handle reject
    console.error(error);
})

Answered By – lufinkey

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published