【问题标题】:Unable to log response from XMLHttpRequest无法记录来自 XMLHttpRequest 的响应
【发布时间】:2021-09-23 21:28:26
【问题描述】:

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

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

【问题讨论】:

  • 我建议允许状态码 300-399,因为它们也是成功的请求。

标签: javascript xmlhttprequest httpresponse


【解决方案1】:

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

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

【讨论】:

  • 是的...非常感谢:)
猜你喜欢
  • 2017-12-02
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多