简体   繁体   中英

Unexpected token g in JSON at position 0 when parsing a file

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => {
   console.log('statusCode:', res.statusCode);
   onsole.log('headers:', res.headers);

   res.on('data', (d) => {
       return msg.reply(JSON.parse(d));
   });

}).on('error', (e) => {
   throw e;
});

I am trying to grab the echo from that php website. I tried Express with app.get() but it couldn't console.log(). I don't know why it didn't error anything with Express but couldn't output.

This thing I'm searching answer for works when I output the "d" using process.stdout.write() . By "d" I mean the d that is here res.on('data', (**d**)) .

I also managed to get this {"type":"Buffer","data":[103,75,68,101,54,78,109,77,117,65,83,67,52,86,81,88,113,106,101,81,77,86,71,66,90,68,112,100,71,76,103,51]} when I stringified the "d" and replied to my message on Discord.

The res in your https.get is a Stream. Now stream has multiple events, data is one of them. When you listen for data event what you get is a chunk of data .

So for a JSON file that you are getting from your server (in this case your php file) d is part of it not all of it.

There is one more event called end , which is, to put it simply, fired when there is no data left in the stream (means all of the data is sent to you). So you need to use end event to actually process the data as all of the data is there with you now.

I am adding a code snippet that might help you:

https
  .get("url", res => {
    console.log("statusCode:", res.statusCode);
    console.log("headers:", res.headers);
    let responseData = "";
    res.on("data", d => {
      //store the chunks in a variable
      responseData += d;
    });
    res.on("end", () => {
      //here now you have all the data, so parse the data
      msg.reply(JSON.parse(responseData));
    });
  })
  .on("error", e => {
    throw e;
  });

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