Response.clone Reads A Body Twice

Clone a Response before reading its body so one consumer parses JSON while another reads text, and observe what happens on re-read.

JavascriptData Fetching

Code

javascriptsnippet
23 lines
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();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Response.clone Reads A Body Twice is built around the function main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Applying it

The primary signature is async function main()

The run prints first as text length:, second as json items:, content-type: — each prefix names the step that produced it.

Statements that matter

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();

Interactive Tools for This Topic

FAQ

What does Response.clone Reads A Body Twice print when run?
Run it as a complete program — the output lines carry labels such as `first as text length:`, `second as json items:`, `content-type:`.