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

Node.js后端XMLHttpRequest onload方法失效,返回undefined求助

解决Node.js中XMLHttpRequest获取API返回undefined的问题

嘿,我帮你找到问题所在啦!你遇到的undefined问题,核心原因是你用的xmlhttprequest这个npm包并不支持responseType = 'json'这个特性——浏览器原生的XMLHttpRequest确实支持,但这个第三方模块只是模拟了基础的XHR功能,没实现JSON自动解析的部分,所以你设置这个属性后完全不生效,request.response自然就是undefined了。

快速修复方案(基于现有模块)

你只需要去掉responseType的设置,手动把返回的文本解析成JSON就行,修改后的代码如下:

// 不用挂到global,直接引入使用更清晰
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();

request.open('GET', 'https://api.github.com/users/hadley/orgs');
request.onload = function() {
  // 先判断请求是否成功
  if (request.status >= 200 && request.status < 300) {
    // 手动解析responseText为JSON对象
    const responseData = JSON.parse(request.responseText);
    console.log(responseData);
  } else {
    console.error('请求失败,状态码:', request.status);
  }
};
// 别忘了处理网络错误情况
request.onerror = function() {
  console.error('发生网络错误,无法连接到API');
};
request.send();

更推荐的替代方案

其实在Node.js环境里,用这种模拟浏览器XHR的模块有点“复古”了,推荐你用更现代、更易用的HTTP客户端:

1. Node.js原生Fetch(v18+自带,无需额外安装)

Node.js从v18版本开始内置了浏览器同款的fetch API,用起来更简洁:

async function getHadleyOrgs() {
  try {
    const response = await fetch('https://api.github.com/users/hadley/orgs');
    if (!response.ok) {
      throw new Error(`请求失败:状态码 ${response.status}`);
    }
    // 直接用response.json()自动解析
    const orgData = await response.json();
    console.log(orgData);
  } catch (err) {
    console.error('获取数据出错:', err.message);
  }
}
getHadleyOrgs();

2. 使用Axios(功能更丰富)

如果需要处理更复杂的HTTP请求(比如拦截器、自动重试等),可以用Axios:
首先安装依赖:

npm i axios

然后编写代码:

const axios = require('axios');

axios.get('https://api.github.com/users/hadley/orgs')
  .then(res => {
    // Axios会自动把响应解析成JSON,直接取res.data就行
    console.log(res.data);
  })
  .catch(err => {
    console.error('请求出错:', err.message);
  });

这样修改后,你就能正常拿到GitHub API返回的组织数据啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:40:56