意外令牌o

时间:2019-08-01 12:59:13

标签: node.js json discord.js

我正在添加一个api,以检查多个mcpe服务器是否在线并以一条消息的形式发送

我已经尝试过在单个消息中执行此操作,并且一切正常

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

    })
  })
}
  

未定义:1   [对象对象]    ^

     

SyntaxError:JSON中位置1处的意外令牌o       在JSON.parse()       在Request._callback(C:\ Users \ Gaming Account \ Desktop \ McfBots \ ServerStatus.js:258:28)       在Request.self.callback(C:\ Users \ Gaming Account \ Desktop \ node_modules \ request \ request.js:185:22)       在Request.emit(events.js:197:13)       应要求。 (C:\ Users \ Gaming Account \ Desktop \ node_modules \ request \ request.js:1161:10)       在Request.emit(events.js:197:13)       在IncomingMessage。 (C:\ Users \ Gaming Account \ Desktop \ node_modules \ request \ request.js:1083:12)       在Object.onceWrapper(events.js:285:13)       在IncomingMessage.emit(events.js:202:15)       在endReadableNT(_stream_visible.js:1132:12)

1 个答案:

答案 0 :(得分:0)

您的响应已经是一个对象,因此无需再次解析它。尝试这样做:

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

这样,只有字符串形式的结果才会被解析。