无法将“ {}”解释为字符串

问题描述

因此,我正在开发一个不和谐的机器人,我想发出一条命令,当用户键入“ .doggo”时,会出现一条随机的狗图像。这是我当前命令的代码。我已经将node-fetch和discord.js库安装到应用程序中。

else if(command === 'doggo') {
    const Fetch = fetch('https://dog.ceo/api/breeds/image/random');
    const embed = new discord.MessageEmbed()
    .setTitle('doggo :dog:')
    .setimage(Fetch);
    message.channel.send(embed);
}

由于某种原因,我在执行命令时收到此警告消息:

(node:10416) UnhandledPromiseRejectionWarning: discordAPIError: Invalid Form Body
embed.image.url: Could not interpret "{}" as string.
    at RequestHandler.execute (C:\Users\jnett\Desktop\demon\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processticksAndRejections (internal/process/task_queues.js:97:5)
(node:10416) 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(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10416) [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.

我的代码有什么问题?我需要做什么来解决它?

解决方法

fetch()调用是异步的,如果不这样处理,将导致您遇到问题。在此处阅读有关Fetch API的更多信息:

https://developers.google.com/web/updates/2015/03/introduction-to-fetch

关于错误消息...

  1. Invalid Form Body是由于尝试嵌入尚未由您的节点应用接收的图像而导致的。通过捕获使用.then(() => { })回调中的fetch调用中的数据的后续代码,可以避免这种情况。

  2. UnhandledPromiseRejectionWarningDeprecationWarning(从技术上来说是第一个错误)是由于缺少.catch()回调。您可以在此处指定如果无法满足获取请求的操作。