最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why fetch Body object can be read only once? - Stack Overflow

programmeradmin3浏览0评论

The fetch specification states that the readable stream Body contains the Body.bodyUsed flag which is initially set to false and then is set to true with a call of any parsing method.

Here's an example:

fetch('/some/path', (res) => {
    // res.body.bodyUsed === false
    res.json();
    // res.body.bodyUsed === true
});

If you try to call a method like res.json() or res.text() once again, an exception is thrown.

The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants? I found no explanation of the matter.

PS. In Chrome (and maybe other browsers), that flag is accessible as res.body.locked.

The fetch specification states that the readable stream Body contains the Body.bodyUsed flag which is initially set to false and then is set to true with a call of any parsing method.

Here's an example:

fetch('/some/path', (res) => {
    // res.body.bodyUsed === false
    res.json();
    // res.body.bodyUsed === true
});

If you try to call a method like res.json() or res.text() once again, an exception is thrown.

The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants? I found no explanation of the matter.

PS. In Chrome (and maybe other browsers), that flag is accessible as res.body.locked.

Share Improve this question edited Mar 15, 2022 at 9:33 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Oct 14, 2017 at 7:57 Phil FilippakPhil Filippak 6731 gold badge10 silver badges22 bronze badges 6
  • 1 why that behavior is used? because it's easy to allow multiple use using Response.clone() - developer.mozilla/en-US/docs/Web/API/Response/clone – Jaromanda X Commented Oct 14, 2017 at 7:59
  • 1 It would require the body to be stored in the res object. – Barmar Commented Oct 14, 2017 at 8:00
  • 3 @JaromandaX yes, but that doesn't answer the next logical question: why to restrict it in first place and implementing clone() instead. – Phil Filippak Commented Oct 14, 2017 at 8:23
  • 2 @PhilFilippak "but that doesn't answer the next logical question: why to restrict it in first place and implementing clone() instead." How do you propose to identify when a ReadableStream read procedure is plete? – guest271314 Commented Oct 14, 2017 at 8:34
  • 1 clone cannot be used (it throws) if the body has been consumed. – Armen Michaeli Commented Feb 10, 2022 at 14:50
 |  Show 1 more ment

1 Answer 1

Reset to default 8

The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants?

It is possible to read Response.body more than once by using Response.clone()

发布评论

评论列表(0)

  1. 暂无评论