← 中文资源

简体中文版本

Response.clone 重复读取响应

在读取 body 前克隆 Response,让一个消费者解析 JSON、另一个读取文本,并观察重复读取的报错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

first as text length: 27
second as json items: 1,2,3
content-type: application/json
re-read failed: TypeError

实现说明

Response.clone 重复读取响应的核心是函数 main。 每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。

使用要点

  • 直接运行文件,输出会带上标签,比如 first as text length:、second as json items:、content-type:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Response.clone 重复读取响应」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 first as text length:、second as json items:、content-type: 这类标签。

签名一览:async function main()

核心语句

const response = new Response(JSON.stringify({ ok: true, items: [1, 2, 3] }), {
  headers: { 'content-type': 'application/json' },
});
const first = await response.text();
const second = await copy.json();

代码示例

async function main() {
  const response = new Response(JSON.stringify({ ok: true, items: [1, 2, 3] }), {
    headers: { 'content-type': 'application/json' },
  });

  // clone 必须在读取 body 之前调用;两个流独立消费
  const copy = response.clone();
  const first = await response.text();
  const second = await copy.json();

  console.log('first as text length:', first.length);
  console.log('second as json items:', second.items.join(','));
  console.log('content-type:', copy.headers.get('content-type'));

  // 已被消费的流再读会抛错
  try {
    await response.text();
  } catch (error) {
    console.log('re-read failed:', error.constructor.name);
  }
}

main();