繁体   English   中英

解析文件时,JSON 中位置 0 处出现意外标记 g

[英]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;
});

我正在尝试从该 php 网站获取回声。 我用 app.get() 尝试过 Express,但它不能使用 console.log()。 我不知道为什么它没有用 Express 出错但无法输出。

当我使用process.stdout.write()输出“d”时,我正在寻找答案。 “d”是指这里的 d res.on('data', (**d**))

我也设法得到这个{"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]}当我将“d”字符串化并在 Discord 上回复我的消息时。

https.getres是一个流。 现在流有多个事件, data就是其中之一。 当您侦听data事件时,您得到的是一个数据块

因此,对于您从服务器获取的 JSON 文件(在本例中为您的 php 文件), d是其中的一部分,而不是全部。

还有一个叫做end事件,简单地说,当流中没有数据时触发(意味着所有数据都发送给你)。 所以您需要使用end事件来实际处理数据,因为所有数据现在都在您身边。

我正在添加一个可能对您有帮助的代码片段:

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;
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM