我不断收到“ JSON输入的意外结尾”

问题描述 投票:0回答:1
app.get("/dashboard", function(req, res) {
  const country = "Singapore";

  // I used a constant in desperation

  const url =
    "https://api.covid19api.com/live/country/" + country;
  https.get(url, function(response) {
    response.on("data", function(data) {
      const caseData = JSON.parse(data);

      // Error stems from here

      res.render("cases", { caseData: caseData });
    });
  });
});
node.js json api
1个回答
0
投票

您在尝试解析消息之前不必等待整个消息。

data事件为HTTP响应中的每个数据块调用。该响应可能不一定适合单个块。

[您必须先等待end事件,然后才能解析JSON ...或者最好使用更高级别的库,例如node-fetch,以获得更舒适的基于Promise的API。

© www.soinside.com 2019 - 2024. All rights reserved.