【问题标题】:TypeError: Cannot read property 'data' of undefined | discord.jsTypeError:无法读取未定义的属性“数据”|不和谐.js
【发布时间】:2021-02-23 01:26:28
【问题描述】:

所以我正在制作一个 Discord 机器人,并且我有一个从 r/memes 获取 meme 的 meme 命令,但有时它会给出 meme,有时代码会崩溃并在控制台中出现此错误:

TypeError: Cannot read property 'data' of undefined

我不太确定它会是什么,所以如果有人可以帮助我,那将有很大帮助。

这是我的!meme 命令代码:

const https = require('https');
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/memes/hot/.json'

module.exports = {
    name: 'meme',
    description: 'sends meme',
    execute(message, args) {

        https.get(url, (result) => {
            var body = ''
            result.on('data', (chunk) => {
                body += chunk
            })

            result.on('end', () => {
                var response = JSON.parse(body)
                var index = response.data.children[Math.floor(Math.random() * 99) + 1].data

                if (index.post_hint !== 'image') {

                    var text = index.selftext
                    const textembed = new Discord.MessageEmbed()
                        .setTitle(subRedditName)
                        .setColor(4388341)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send(textembed)
                }

                var image = index.preview.images[0].source.url.replace('&', '&')
                var title = index.title
                var link = 'https://reddit.com' + index.permalink
                var subRedditName = index.subreddit_name_prefixed

                if (index.post_hint !== 'image') {
                    const textembed = new Discord.MessageEmbed()
                        .setTitle(subRedditName)
                        .setColor(4388341)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send(textembed)
                }
                console.log(image);
                const imageembed = new Discord.MessageEmbed()
                    .setTitle(subRedditName)
                    .setImage(image)
                    .setColor(4388341)
                    .setDescription(`[${title}](${link})`)
                    .setURL(`https://reddit.com/${subRedditName}`)
                message.channel.send(imageembed)
            }).on('error', function (e) {
                console.log('Got an error: ', e)
            })
        })
    },
}

【问题讨论】:

  • response.data.children[Math.floor(Math.random() * 99) + 1].data response.data 未定义或 children.data 未定义检查

标签: javascript node.js discord.js


【解决方案1】:

这是因为您设置了一个硬编码数字 (99) 以从 response.data.children 数组中获取一个随机元素。我刚刚检查了该数组的长度,它是 26。如果你的随机数大于那个(并且你正在生成一个介于 1 和 100 之间的随机数),response.data.children[randomNumber] 将是 undefined .

尝试使用数组的长度作为最大数量,这样它就不会超过元素的数量:

let index =
  response.data.children[
    Math.floor(Math.random() * response.data.children.length)
  ].data;

完整代码:

module.exports = {
  name: 'meme',
  description: 'sends meme',
  execute(message, args) {
    https.get(url, (result) => {
      let body = '';

      result.on('data', (chunk) => {
        body += chunk;
      });

      result
        .on('end', () => {
          const response = JSON.parse(body);
          const index =
            response.data.children[
              Math.floor(Math.random() * response.data.children.length)
            ].data;

          const image = index.preview.images[0].source.url.replace(
            '&',
            '&',
          );
          const title = index.title;
          const link = 'https://reddit.com' + index.permalink;
          const subRedditName = index.subreddit_name_prefixed;

          if (index.post_hint !== 'image') {
            const text = index.selftext;
            const textembed = new Discord.MessageEmbed()
              .setTitle(subRedditName)
              .setColor(4388341)
              .setDescription(`[${title}](${link})\n\n${text}`)
              .setURL(`https://reddit.com/${subRedditName}`);

            message.channel.send(textembed);
          }

          const imageembed = new Discord.MessageEmbed()
            .setTitle(subRedditName)
            .setImage(image)
            .setColor(4388341)
            .setDescription(`[${title}](${link})`)
            .setURL(`https://reddit.com/${subRedditName}`);

          message.channel.send(imageembed);
        })
        .on('error', function (e) {
          console.log('Got an error: ', e);
        });
    });
  },
};

【讨论】:

  • 好吧,所以我将它添加到代码中,但现在我得到了,ReferenceError: response is not defined at response.data.children[
  • 这很奇怪。你能用我的execute 函数检查我的更新答案吗?
  • 我似乎无法复制上面的执行,你能把它和完整的代码一起发送吗?
  • 是的,这似乎正在工作。如果发生其他任何事情,我会及时通知您。感谢您的帮助。
猜你喜欢
  • 2020-11-10
  • 2020-11-11
  • 2021-04-15
  • 2021-05-10
  • 1970-01-01
  • 2021-05-25
  • 2021-10-03
  • 2020-05-22
  • 1970-01-01
相关资源
最近更新 更多