简体   繁体   中英

How to fix: “undefined response from fetch” Javascript

Been trying to fetch a link/image from an open API from the following guide: https://discordjs.guide/additional-info/rest-api.html#using-node-fetch but it is not working. I keep getting an undefined response.

Already tried making async functions and so on but not getting any closer. Also surrounded it by try-catch clausule to debug but not finding the answer.


    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);

        },
    };

And this is where it is used:


    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!');
            }

        }
    );

Expected result following the Guide should be a random cat image.

The documentation you're using is incorrect in a couple of ways:

const {body} = await fetch('https://aws.random.cat/meow').then(response => response.json())
  1. That line assumes fetch doesn't fail (with a 404, for instance). This is such a common mistake that I've written it up on my anemic little blog . fetch 's promise only rejects on network errors , not HTTP errors. You have to check response.ok or response.status .

  2. That the parsed result will have a body property.

  3. It uses then in an async function, which makes very little sense.

But if I go to https://aws.random.cat/meow , I get this JSON:

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

There's no body there, which is why you get undefined for it.

Here's an example fixing all three issues:

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

The response from the api is

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

And you are saying it is

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

So you need to dump the brackets

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

or you need to look for file instead

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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