0

I'm developing a discord bot that has a command which randomly generates images of cats.

This is my code:

else if(command === 'kitteh') {
        fetch('https://api.thecatapi.com/v1/images/search?format=json', {   
        headers: {
                'x-api-key' : 'MY_API_KEY',
            }
        })
        .then(
            function(response) {
                response.json().then(function(data) {
                    const embed = new Discord.MessageEmbed()
                    console.log(data.url)
                    .setTitle('kitteh :cat:')
                    .setImage(data.url)
                    .setFooter(`${message.author.tag} | powered by TheCatAPI (thecatapi.com)`);
                    message.channel.send(embed);
                });
            } 
        ); 

For some reason, the api does not send me the url of the image, and the console prints undefined, and the discord bot shows no image.

lapetus
  • 1
  • 1
  • 1
    The API returns an array, not an object. – str Aug 27 '20 at 06:44
  • What am I supposed to do with that? I've looked at https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json and it was no help at all. – lapetus Aug 27 '20 at 07:03
  • @lapetus you are mishandling the response, try this fetch('https://api.thecatapi.com/v1/images/search?format=json', { headers: { 'x-api-key' : 'MY_API_KEY', } }) .then( function(response) { return response.json(); } ).then(data => { console.log(data) console.log("URL is: ", data[0].url) }); – Shubham Srivastava Aug 27 '20 at 07:05

1 Answers1

0

Here is the raw call using the returned array

fetch('https://api.thecatapi.com/v1/images/search?format=json')
  .then(
    function(response) {
      response.json().then(function(data) {
        data.forEach(cat => {
          const img = new Image()
          img.onload=function() {
            document.body.appendChild(img)
          };
          img.src = cat.url
        })
      })
    });
mplungjan
  • 169,008
  • 28
  • 173
  • 236