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

Node.js Fetch读取ReadableStream时响应不完整的问题

Node.js fetch POST请求ReadableStream响应不完整的解决方法

你当前的问题根源是只读取了ReadableStream的第一个数据块,当响应内容分块传输时,单次read()只能拿到部分内容,导致JSON字符串不完整,最终触发Unexpected end of JSON input错误。

修复方案一:手动循环读取所有流数据

需要持续调用read()直到流的done状态为true,将所有数据块拼接后再解析:

static async postData(url = "") {
  const response = await fetch(url, {
    method: "POST",
    mode: "same-origin",
    cache: "default",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    redirect: "follow",
    referrerPolicy: "no-referrer",
    // 记得补充body参数,POST请求通常需要传请求体
    // body: JSON.stringify(dados),
  });

  if (!response.body) {
    throw new Error("响应流为空");
  }

  const reader = response.body.getReader();
  const chunks = [];
  let result;

  // 循环读取所有数据块
  do {
    result = await reader.read();
    if (result.value) {
      chunks.push(result.value);
    }
  } while (!result.done);

  // 合并所有数据块为Buffer,再转成UTF-8字符串
  const jsonBuffer = Buffer.concat(chunks);
  const jsonString = jsonBuffer.toString("utf8");
  console.log(jsonString);
  return JSON.parse(jsonString);
}

修复方案二:使用fetch原生的json()方法(更简便)

fetch的Response对象已经内置了json()方法,它会自动处理流的读取和JSON解析,无需手动操作流:

static async postData(url = "") {
  const response = await fetch(url, {
    method: "POST",
    mode: "same-origin",
    cache: "default",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    redirect: "follow",
    referrerPolicy: "no-referrer",
    // 补充POST请求的body参数
    // body: JSON.stringify(dados),
  });

  // 直接调用json()方法,自动完成流读取和解析
  return await response.json();
}

额外提示

  • 你当前代码中注释掉了body参数,POST请求通常需要传递请求体,记得根据实际需求恢复该参数,否则服务器可能无法处理请求。
  • 建议添加响应状态码判断,比如if (!response.ok) throw new Error('请求失败'),避免在请求出错时继续解析数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:45:42