aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/response/body/index.html
blob: ffd78b8dfe9311060060ff194766a2360057d6a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
---
title: Response.body
slug: Web/API/Response/body
translation_of: Web/API/Response/body
tags:
  - API
  - Fetch
  - Property
  - Reference
  - Streams
  - Response
browser-compat: api.Response.body
---
<div>{{APIRef("Fetch")}}</div>

<p>{{domxref("Response")}} mixin的只读getter属性 <strong><code>body</code></strong> 用于暴露其body内容的{{domxref("ReadableStream")}}(流读取)。</p>

<h2 id="语法">语法</h2>

<pre class="brush: js">var stream = responseInstance.body;</pre>

<h3 id="Value">Value</h3>

<p>一个 {{domxref("ReadableStream")}}.</p>

<h2 id="例程">例程</h2>

<p>在我们的 <a href="https://mdn.github.io/dom-examples/streams/simple-pump.html">simple stream pump</a> 例程中我们fetch一个图片地址,使用<code>response.body</code>暴露响应的流,用{{domxref("Response.getReader()", "ReadableStream.getReader()")}}创建一个读取器,然后将其置入第二个自定义读取流中——有效的创建了一个完全相同的图片副本。</p>

<pre class="brush: js">const image = document.getElementById('target');

// 请求原始图片
fetch('./tortoise.png')
// 取出body
.then(response =&gt; response.body)
.then(body =&gt; {
  const reader = Response.getReader();

  return new ReadableStream({
    start(controller) {
      return pump();

      function pump() {
        return reader.read().then(({ done, value }) =&gt; {
          // 读不到更多数据就关闭流
          if (done) {
            controller.close();
            return;
          }

          // 将下一个数据块置入流中
          controller.enqueue(value);
          return pump();
        });
      }
    }
  })
})
.then(stream =&gt; new Response(stream))
.then(response =&gt; response.blob())
.then(blob =&gt; URL.createObjectURL(blob))
.then(url =&gt; console.log(image.src = url))
.catch(err =&gt; console.error(err));</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范</th>
   <th scope="col">状态</th>
   <th scope="col">备注</th>
  </tr>
  <tr>
   <td>{{SpecName('Fetch','#dom-body-body','body')}}</td>
   <td>{{Spec2('Fetch')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<div>{{Compat("api.Response.body")}}</div>

<p> </p>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li>
 <li><a href="/en-US/docs/Web/API/Streams_API">Streams API</a></li>
 <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li>
</ul>