0
votes

Im adding an api to check if multiple mcpe servers are online and send it in one message

Ive tried doing it in single messages and it all works

'test': async (msg) => {
  request("https://api.mcsrvstat.us/2/mcfcraft.xyz", function(errHub, responseHub, statusHub) {
    const bodyHub = JSON.parse(responseHub)
    request("https://api.mcsrvstat.us/2/173.249.34.88:25879", function(errFac, responseFac, statusFac) {
      const bodyFac = JSON.parse(responseFac)

      let embed = new Discord.RichEmbed()
      .setTitle("Server status response")
      .setColor("PURPLE")
      .setDescription("Requested response from our network.")
      if(bodyHub.online === true)  {
        embed.addField("Server: HUB", `Server status: Online\nPlayers: ${bodyHub.players.online}/${bodyHub.players.max}\nMOTD: ${bodyHub.motd.raw}`)
      } else {
        embed.addField("Server: HUB", `Server status: Offline\nPlayers: 0/0\nMOTD: N/A`)
      }

      if(bodyFac.online === true) {
        embed.addField("Server: FACTIONS", `Server status: Online\nPlayers: ${bodyFac.players.online}/${bodyFac.players.max}\nMOTD: ${bodyFac.motd.raw}`)
      } else {
        embed.addField("Server: FACTIONS", `Server status: Offline\nPlayers: 0/0\nMOTD: N/A`)
      }

      msg.channel.send(embed)

    })
  })
}

undefined:1 [object Object] ^

SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at Request._callback (C:\Users\Gaming Account\Desktop\McfBots\ServerStatus.js:258:28) at Request.self.callback (C:\Users\Gaming Account\Desktop\node_modules\request\request.js:185:22) at Request.emit (events.js:197:13) at Request. (C:\Users\Gaming Account\Desktop\node_modules\request\request.js:1161:10) at Request.emit (events.js:197:13) at IncomingMessage. (C:\Users\Gaming Account\Desktop\node_modules\request\request.js:1083:12) at Object.onceWrapper (events.js:285:13) at IncomingMessage.emit (events.js:202:15) at endReadableNT (_stream_readable.js:1132:12)

1
Your result is already an object, you don't need to JSON.parse it. - str
@str when I put responseFac.body.online it comes out undefined - YxriDev
@str even when I remove the parse - YxriDev

1 Answers

0
votes

Your response is an object already so there's no need to parse it again. Try doing it like this:

const bodyHub = typeof responseHub === 'string' ? JSON.parse(responseHub) : responseHub;
...
const bodyFac = typeof responseFac === 'string' ? JSON.parse(responseFac) : responseFac;

This way the result will be parsed only if it's a string.