无法记录来自 XMLHttpRequest 的响应

Unable to log response from XMLHttpRequest

我已经为 GET 请求创建了一个 XMLHttpRequest class 包装器。我无法控制台记录我得到的响应。我在代码中遗漏了什么吗?

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

您似乎将回调传递给您的方法调用,而不是使用您返回的承诺。你的电话应该更像:

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