简体   繁体   English

尝试从 node.js 中的 url 获取时,获取“无法读取未定义的属性‘长度’”

[英]getting 'Cannot read property 'length' of undefined' when trying to fetch from an url in node.js

So i was trying to create a Discord-Bot which is able to lookup definitions on urbandictionary.. but i am getting an error after trying to fetch the json from their api.所以我试图创建一个 Discord-Bot,它能够在 Urbandictionary 上查找定义..但是在尝试从他们的 api 获取 json 后我收到了一个错误。

const args = Array.prototype.slice.call(commandArgs);
    if (!args.length) {
    return message.channel.send('You need to supply a search term!');
    }

    const query = querystring.stringify({ term: args.join(' ') });

    const body  = await fetch(`https://api.urbandictionary.com/v0/define${query}`).then(response => response.json());

    console.log(fetch(`https://api.urbandictionary.com/v0/define${query}`).then(response => response.json()));

    if (!body.list.length) {
        return message.channel.send(`No results found for **${args.join(' ')}**.`);
    }

    const [answer] = body.list;

    const embed = new Discord.RichEmbed()
        .setColor('#EFFF00')
        .setTitle(answer.word)
        .setURL(answer.permalink)
        .addField('Definition', trim(answer.definition, 1024))
        .addField('Example', trim(answer.example, 1024))
        .addField('Rating', `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`);

    message.channel.send(embed);
    }

the error looks like this:错误如下所示:

    (node:11948) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at Client.client.on (C:\Users\Johannes\Desktop\Vladimir\main.js:176:18)
    at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:11948) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11948) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

the console.log() function in the middle just says: "Promise { pending }"中间的 console.log() 函数只是说:“Promise { pending }”

If we never encountered hard problems coding we probably aren't trying hard enough.如果我们从未遇到过编码难题,那么我们可能还不够努力。 And instead of giving up you asked for help.而不是放弃,你寻求帮助。 Being smart enough to do all that puts you in a good spot.足够聪明,可以做所有让你处于有利位置的事情。

In your code you have an await command.在您的代码中,您有一个 await 命令。 For this to work async needs to be placed before the beginning of the outer function.为此,异步需要放置在外部函数的开头之前。 Keep in mind that await only works with promises.请记住, await 仅适用于承诺。 Also note that you have fetch once next to body and then again in the console statement.另请注意,您在 body 旁边获取了一次,然后在控制台语句中再次获取。 This would cause two requests when we only need one.当我们只需要一个请求时,这将导致两个请求。 Hope the updated snippet below helps you out.希望下面更新的片段可以帮助您。

getUrbanDictionaryDefs = async function() {
  const args = Array.prototype.slice.call(commandArgs);
  if (!args.length) {
    return message.channel.send("You need to supply a search term!");
  }

  const query = querystring.stringify({ term: args.join(" ") });

  let body;

  try {
    body = await fetch(`https://api.urbandictionary.com/v0/define${query}`);
  } catch (err) {
    console.log(err);
    return;
  }

  body = body.json();

  console.log(body);

  if (!body.list.length) {
    return message.channel.send(`No results found for **${args.join(" ")}**.`);
  }

  const [answer] = body.list;

  const embed = new Discord.RichEmbed()
    .setColor("#EFFF00")
    .setTitle(answer.word)
    .setURL(answer.permalink)
    .addField("Definition", trim(answer.definition, 1024))
    .addField("Example", trim(answer.example, 1024))
    .addField(
      "Rating",
      `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`
    );

  message.channel.send(embed);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM