用 js fetch 写一个 stream 请求的代码

用 js fetch 写一个 stream 请求的代码
用户941888011
2023年09月15日
|
浏览 519

当使用JavaScript的Fetch API进行流请求时,你可以通过以下代码实现:

复制代码
// 创建一个ReadableStream对象
const stream = new ReadableStream({
  start(controller) {
    // 发起请求
    fetch('your_url_here')
      .then(response => {
        const reader = response.body.getReader();

        // 定义读取数据的函数
        function read() {
          reader.read().then(({ done, value }) => {
            // 如果读取结束,则关闭流
            if (done) {
              controller.close();
              return;
            }

            // 处理获取到的数据
            console.log(value);

            // 继续读取下一部分数据
            read();
          });
        }

        // 开始读取数据
        read();
      })
      .catch(error => {
        console.error('Error:', error);
        controller.error(error);
      });
  }
});

// 使用stream对象
const response = new Response(stream, { headers: { "Content-Type": "text/html" } });
const html = new HTMLDivElement();
html.innerHTML = `<p>Loading...</p>`;
document.body.appendChild(html);
html.appendChild(response.body);

这段代码将发起一个流请求并将响应数据打印到控制台。你可以根据自己的需求对获取到的数据进行处理。

请注意,以上代码仅为示例,你需要将your_url_here替换为你实际请求的URL。另外,如果你想在浏览器中运行此代码,需要确保浏览器支持Fetch API和ReadableStream API。

希望这个回答能帮到你!如果你还有其他问题,请随时提问。

我要提问
复制内容
分享给好友
AI编程问答网 免责声明:
以上内容除特别注明外均来源于网友提问,AI编程问答网回答,权益归原著者所有;