[英]getting 'Cannot read property 'length' of undefined' when trying to fetch from an url in node.js
所以我试图创建一个 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);
}
错误如下所示:
(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.
中间的 console.log() 函数只是说:“Promise { pending }”
如果我们从未遇到过编码难题,那么我们可能还不够努力。 而不是放弃,你寻求帮助。 足够聪明,可以做所有让你处于有利位置的事情。
在您的代码中,您有一个 await 命令。 为此,异步需要放置在外部函数的开头之前。 请记住, await 仅适用于承诺。 另请注意,您在 body 旁边获取了一次,然后在控制台语句中再次获取。 当我们只需要一个请求时,这将导致两个请求。 希望下面更新的片段可以帮助您。
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.