首页 > 解决方案 > 尝试访问 hypixel api 中的“pricePerUnit”时,出现错误:TypeError: Cannot read property 'pricePerUnit' of undefined

问题描述

{"success":true,"lastUpdated":1598982272495,"products":{"BROWN_MUSHROOM":{"product_id":"BROWN_MUSHROOM","sell_summary":[{"amount":160,"pricePerUnit":13.9,"orders":1},{"amount":28503,"pricePerUnit":13.8,"orders":2},{"amount":71483,"pricePerUnit":13.4,"orders":3}, 这就是api所说的所以我认为我可以直接得到“pricePerUnit。但我得到了错误TypeError: Cannot read property 'pricePerUnit' of undefined

我的代码是:```client.on("message", message => { if (message.author.bot) return;

const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();

if (command === "bazaar") {
    let product = args[0];

    fetch(`https://api.hypixel.net/skyblock/bazaar/product?key=${key}`)
    .then(result => result.json())
    .then(({ BROWN_MUSHROOM }) => {
        // Log the player's username
        message.reply(BROWN_MUSHROOM.pricePerUnit)
    })

}

})```

有人知道如何帮助吗?

标签: javascriptapidiscord.js

解决方案


尝试将您的最后一个块修改为:

.then(({ products: { BROWN_MUSHROOM } }) => {
    // Log the player's username
    message.reply(BROWN_MUSHROOM.pricePerUnit)
})

因为BROWN_MUSHROOM似乎在products字段下。


推荐阅读