簡體   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