diff options
Diffstat (limited to 'files/zh-cn/web/api/response/body/index.html')
-rw-r--r-- | files/zh-cn/web/api/response/body/index.html | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/files/zh-cn/web/api/response/body/index.html b/files/zh-cn/web/api/response/body/index.html new file mode 100644 index 0000000000..ffd78b8dfe --- /dev/null +++ b/files/zh-cn/web/api/response/body/index.html @@ -0,0 +1,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 => response.body) +.then(body => { + const reader = Response.getReader(); + + return new ReadableStream({ + start(controller) { + return pump(); + + function pump() { + return reader.read().then(({ done, value }) => { + // 读不到更多数据就关闭流 + if (done) { + controller.close(); + return; + } + + // 将下一个数据块置入流中 + controller.enqueue(value); + return pump(); + }); + } + } + }) +}) +.then(stream => new Response(stream)) +.then(response => response.blob()) +.then(blob => URL.createObjectURL(blob)) +.then(url => console.log(image.src = url)) +.catch(err => 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> |