【问题标题】:TypeError: Cannot destructure property `body` of 'undefined' or 'null'TypeError:无法解构“未定义”或“空”的属性“主体”
【发布时间】:2020-05-28 22:58:20
【问题描述】:

我在控制台出现以下错误:

TypeError:无法解构“未定义”的属性body 或 '空'。

这是我的代码:

var { body } = await snekfetch.get(`https://api.roblox.com/users/get-by-username?username=${userArray[i]}`).catch((err) => console.log('caught it'));
        if (body.success === false){
          var errorEmbed = new Discord.RichEmbed()
            .setColor(0xff4040)
            .setDescription(`:warning: **${userArray[i]} doesn't exist on ROBLOX** :warning:`);
            await message.channel.send(errorEmbed);

【问题讨论】:

  • 添加 try and catch 并检查控制台是否有任何错误。
  • 这样能抓到他们吗? .catch((err) => console.log('caught it'));
  • 使用,尝试 { } catch(error) {}.
  • 那么只有var { body } = await snekfetch.get(api.roblox.com/users/get-by-username?username=${userArray[i]}).catch((err) => console.log('caught it')); 还是整个代码?
  • 添加了答案

标签: javascript


【解决方案1】:

试试这个。

try {
  var response = await snekfetch.get(
    `https://api.roblox.com/users/get-by-username?username=${userArray[i]}`
  );
  if (response && response.body && response.body.success) {
    var errorEmbed = new Discord.RichEmbed()
      .setColor(0xff4040)
      .setDescription(
        `:warning: **${userArray[i]} doesn't exist on ROBLOX** :warning:`
      );
    await message.channel.send(errorEmbed);
  } else {
    console.log('Error');
  }
} catch (error) {
  console.log(error);
}


【讨论】:

  • 出现新错误:SyntaxError: Unexpected token 'else'
  • 我有。它显示另一个错误:Unexpected token 'else'
  • get 调用很多,你必须像上面那样更改所有调用。
  • 您介意为我做一些类似示例的操作吗,因为我对 Javascript 了解不多?谢谢
  • 抱歉耽搁了。我已经为您提供了答案中的示例。
猜你喜欢
  • 2018-09-30
  • 2021-03-21
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2019-07-15
  • 2020-01-24
相关资源
最近更新 更多