You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用COVID 19 API解析JSON时遭遇Unexpected end of JSON input错误

解决COVID-19 API数据解析的JSON错误问题

嘿,我一眼就看出问题所在啦!你遇到的两个状况其实是同一个原因导致的:HTTP响应的data事件是分块触发的,并不是一次性返回完整的JSON数据。

问题根源拆解

  • 当你用https.get请求API时,服务器会把数据拆分成多个小块(Buffer对象)逐步返回,response.on("data")每次只会拿到其中一块。直接对这部分不完整的数据执行JSON.parse,自然会报「Unexpected end of JSON input」错误。
  • 直接打印data显示十六进制,是因为data本身是Node.js的Buffer对象,它的默认输出格式就是十六进制。

修复后的完整代码

你需要把所有接收到的数据块拼接起来,等整个响应接收完成(也就是end事件触发时)再进行JSON解析:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const https = require("https"); // 建议加上const,避免全局变量污染

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function (req, res) {
  const url = "https://api.covid19api.com/summary";
  let responseData = []; // 用来存储所有数据块的数组

  https.get(url, function (response) {
    // 每收到一块数据,就添加到数组中
    response.on("data", function (chunk) {
      responseData.push(chunk);
    });

    // 所有数据接收完成后触发end事件
    response.on("end", function () {
      try {
        // 把所有Buffer块拼接成完整Buffer,再转成字符串解析为JSON
        const covidData = JSON.parse(Buffer.concat(responseData).toString());
        console.log(covidData);
        // 如果需要给前端返回数据,可在这里添加res.send(covidData)
      } catch (error) {
        console.error("JSON解析失败:", error);
      }
    });

    // 处理请求过程中的错误
    response.on("error", function (error) {
      console.error("请求API出错:", error);
    });
  });
});

app.listen(3000, function () {
  console.log("server is running on port 3000");
});

额外优化小提示

  • 给https和url加上const声明,避免意外的全局变量污染问题。
  • 用try/catch包裹JSON解析逻辑,能更优雅地处理解析失败的场景。
  • 如果后续需要频繁调用API,推荐使用axios或node-fetch这类HTTP客户端库,它们会自动帮你处理数据拼接和JSON解析,不用手动处理分块逻辑。

内容的提问来源于stack exchange,提问作者harshvardhan mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:07:31