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

Node.js调用Hypixel bazaar接口获取pricePerUnit报undefined错误如何解决

错误原因

你遇到的报错本质是部分Hypixel bazaar商品没有在售/求购挂单,对应的sell_summary或buy_summary是空数组,此时读取[0]会得到undefined,再尝试访问undefined的pricePerUnit属性就会触发该报错。你之前单独测试的都是有挂单的热门商品,所以不会触发问题,遍历全量商品时碰到无挂单的冷门商品就会报错。

解决方案

可以用可选链操作符兼容空数组的场景,再增加缺省值兜底,避免报错。同时axios默认会自动解析JSON返回值,不需要手动做序列化+反序列化的冗余操作,修改后的代码如下:

const axios = require("axios").default;

async function bazaar() {
  try {
    const res = await axios.get(
      "https://api.hypixel.net/skyblock/bazaar?key=xxxxxxx"
    );
    const newJson = res.data;
    const array = [];
    for (const i in newJson.products) {
      const product = newJson.products[i];
      const productName = product.product_id;
      // 可选链+默认值兜底,空挂单场景默认返回0,可按需改为null等自定义标记
      const sellSummary = product.sell_summary[0]?.pricePerUnit ?? 0;
      const buySummary  = product.buy_summary[0]?.pricePerUnit ?? 0;
      const mathSummary = buySummary - sellSummary;
      array.push(
        productName,
        sellSummary,
        buySummary
      );
    }
    console.log(array);
  } catch (error) {
    console.log(error);
  }
}

如果你的Node版本过低不支持可选链操作符,可以用传统判空写法替换取值逻辑:

const sellSummary = product.sell_summary.length > 0 ? product.sell_summary[0].pricePerUnit : 0;
const buySummary  = product.buy_summary.length > 0 ? product.buy_summary[0].pricePerUnit : 0;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:57:04