You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

封装的XMLHttpRequest GET请求类无法打印响应,代码存在什么问题?

问题原因及修复方案

1. 核心错误点

  • 调用方式不匹配:你封装的HttpCall.get返回的是Promise实例,你传入的第二个回调参数不会被执行,只会被方法识别为headers参数
  • XHR方法执行顺序错误:XMLHttpRequest.setRequestHeader()必须在open()调用完成后执行,你当前的代码顺序会抛出状态错误,导致请求直接终止

2. 修正后的代码

HttpWrapper.js

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

      xhr.onreadystatechange = function () {
        //请求已发送、服务器完成返回响应、浏览器已完成响应内容下载
        if (4 === xhr.readyState) {
          if (200 <= xhr.status && xhr.status < 300) {
            resolve(xhr.response);
          } else {
            reject(xhr.status);
          }
        }
      };

      // 调整顺序:先调用open 再设置请求头
      xhr.open("GET", endpoint, true);

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

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

export default HttpCall;

index.js(Promise.then 调用方式)

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

HttpCall.get(
  BASE_BACKEND_URL + "?event_family=session&source_id=guru1"
)
.then(function (response) {
  console.log(response);
})
.catch(function (errStatus) {
  console.error('请求失败,状态码:', errStatus);
});

如果习惯用async/await写法也可以替换index.js内容:

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

async function fetchData() {
  try {
    const response = await HttpCall.get(
      BASE_BACKEND_URL + "?event_family=session&source_id=guru1"
    );
    console.log(response);
  } catch (errStatus) {
    console.error('请求失败,状态码:', errStatus);
  }
}

fetchData();

内容的提问来源于stack exchange,提问作者Gurupal singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:27:03