Daniel Weatherall
Daniel Weatherall

Reputation: 11

TypeError: Cannot read property 'body' of null

Struggling to get this one to work now;

const superagent = require("snekfetch");
const Discord = require('discord.js')


module.exports = {
  name: "cat",
  category: "fun",
description: "Sends a random image of a cat",
usage: "[command]",
run: async (client, message, args, level) => {
//command
superagent.get('https://nekos.life/api/v2/img/meow')
    .end((err, response) => {
  const lewdembed = new Discord.MessageEmbed()
  .setTitle("Random cat")
  .setImage(response.body.url)
  .setColor(`#00FF00`)
  .setFooter(`owo`)
  .setURL(response.body.url);
message.channel.send(lewdembed);
})
}
};

Throwing up this error;

TypeError: Cannot read property 'body' of null
    at /home/runner/Manias-Bot/commands/fun/cat.js:16:22
    at /home/runner/Manias-Bot/node_modules/snekfetch/src/index.js:212:22

I can see the error is with (response.body.url), but unsure how to solve this. Any help?

Upvotes: 1

Views: 692

Answers (1)

Fraser
Fraser

Reputation: 17039

Firstly, snekfetch has been deprecated, you should use node-fetch instead.

See https://www.npmjs.com/package/snekfetch

Secondly, the error is because response is null - almost certainly because you have an error when trying to get that resource. My guess would be ECONNREFUSED but you can confirm this by checking the value of err and response in your get, i.e.

superagent.get('https://nekos.life/api/v2/img/meow')
  .end((err, response) => {
    console.log(err, response)
  })

This give me...

[Error: connect ECONNREFUSED 0.0.0.0:443] {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '0.0.0.0',
  port: 443
} null

So as you can see - the server is refusing the request and the response is null

To fix this you should use a package that isn't deprecated and make sure you are trying to fetch a resource that you have permission/access to get.

When fetching anything - it is always a good idea to check to see if there are any errors before trying to do something with the expected result.

Upvotes: 1

Related Questions