【问题标题】:How to fix: "undefined response from fetch" Javascript如何修复:“来自提取的未定义响应”Javascript
【发布时间】:2019-09-11 18:37:43
【问题描述】:

一直在尝试从以下指南的开放 API 中获取链接/图像:https://discordjs.guide/additional-info/rest-api.html#using-node-fetch 但它不工作。我不断收到未定义的响应。

已经尝试过制作异步函数等,但没有更进一步。 还用try-catch clausule包围它来调试但找不到答案。


    module.exports = {
        name: 'poes',
        description: 'Laat een random poes foto zien',
        async execute(message, args) {

                const fetch = require('node-fetch');
                const {body} = await fetch('https://aws.random.cat/meow').then(response => response.json());

                message.channel.send(body.file);

        },
    };

这就是它的用途:


    client.on('message', message => {
            if (!message.content.startsWith(prefix) || message.author.bot) return;

            const args = message.content.slice(prefix.length).split(/ +/);
            const command = args.shift().toLowerCase();

            if (!client.commands.has(command)) return;

            try {
                client.commands.get(command).execute(message, args);
            } catch (error) {
                console.error(error);
                message.reply('there was an error trying to execute that command!');
            }

        }
    );

按照指南的预期结果应该是随机的猫图像。

【问题讨论】:

  • 你的json里面有body吗?
  • 你是对的,它里面没有“body”。

标签: javascript api asynchronous fetch


【解决方案1】:

您使用的文档在以下几个方面不正确:

const {body} = await fetch('https://aws.random.cat/meow').then(response => response.json())
  1. 该行假定fetch 不会失败(例如,使用 404)。这是一个常见的错误,我written it up on my anemic little blogfetch 的承诺只拒绝网络错误,而不是 HTTP 错误。您必须检查response.okresponse.status

  2. 解析结果将具有body 属性。

  3. 它在async 函数中使用then,这没什么意义。

但如果我转到https://aws.random.cat/meow,我会得到这个 JSON:

{"file":"https:\/\/purr.objects-us-east-1.dream.io\/i\/img_20131111_094048.jpg"}

那里没有body,这就是为什么你会得到undefined

以下是解决所有三个问题的示例:

const response = await fetch('https://aws.random.cat/meow');
if (!response.ok) {
    throw new Error("HTTP status " + response.status);
}
const body = await response.json();
//    ^---^---- no { and }, we don't want to destructure

【讨论】:

  • 感谢您的回复,我会在一分钟内尝试并通知您!
  • 非常感谢这个工作!不过,我确实有一个问题:“该函数还需要异步吗?
  • @Darcula - 如果你打算使用await,是的,因为await 仅在async 函数中有效。另一种方法是在非async 函数中返回fetch('https://aws.random.cat/meow').then(response => { if (!response.ok) { throw new Error("HTTP status " + response.status); } return response.json(); }); 的结果(这是JSON 的承诺)。
  • 我使用了您提供的答案!错误地点击了另一个答案。所以这应该意味着所有问题都解决了对吧? (将阅读您提供的链接!)
  • @Darcula - 应该是这个意思,是的! :-)
【解决方案2】:

来自api的响应是

{
  "file": "https://purr.objects-us-east-1.dream.io/i/r958B.jpg"
}

你说的是

{ 
  "body" : {
    "file" : ""
  }
}

所以你需要转储括号

const body = await fetch('https://aws.random.cat/meow')
    .then(response => response.json());

或者你需要寻找文件来代替

const { file } = await fetch('https://aws.random.cat/meow')
    .then(response => response.json());
console.log(file)

【讨论】:

  • 感谢您的回复,我会在几分钟内试试这个!
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 2020-04-08
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多