Search code examples
javascriptxmlhttprequesthttpresponse

Unable to log response from XMLHttpRequest


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);
    })