当前位置:   article > 正文

【JS】获取接口返回 EventStream 结构的数据(即接收读取 stream 流)_前端调用post接口,返回eventstream,怎么处理

前端调用post接口,返回eventstream,怎么处理

文章目录

EventStream 是一种服务器推送的数据格式,可以用于实时数据传输。

  • 接口返回的示例图
    在这里插入图片描述

  • 获取示例:

// 这里的 url 为虚拟的,仅供演示用
fetch(`https://test.cn.com/api/agent/2`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        mode: 'cors',
        credentials: 'include',
        body: JSON.stringify({
          messages: '测试文案,可修改',
          id: 76,
        }),
      })
        .then((response) => {
        const decoder = new TextDecoder('utf-8');
        let buffer = []
        // 获取可读流
        const reader = response.body.getReader();
    
        // 读取数据
        function read() {
          return reader.read().then(({ done, value }) => {
            if (done) {
              // 这里就能拿到完成的 buffer
              console.log('Stream 已经读取完毕', buffer);
              // 如果需要使用到完整的数据,可在这里使用,useData是你要使用数据来干嘛的函数
              useData(buffer)
              return buffer;
            }
            // 读取每段流的数据块
    		const chunk = decoder.decode(value, { stream: false });
            // 由于数据块中可能包含多段数据,需要额外拆分成单段数据,具体因单段数据结构而异,这里不演示
            // 例如正常是:'{a: 1}' 结构,我们使用 JSON.parse 就能转换成对象结构。
            // 结果返回了 '{a: 1}{a: 2}' 两段拼接在一起的数据,这种需要自行处理为:[{a: 1}, {a: 2}]
            const list = parseMultiJson(chunk); // 封装一个自定义函数parseMultiJson去处理.
            // 如果需要每获取一段数据,就使用到一段数据,那就在这里使用,useData是你要使用这段数据来干嘛的函数
            useData(list)
            // 把处理好后的数据合并到 buffer中
            buffer = buffer.concat(chunk);
            // 继续读取
            return read();
          });
        }
        // 开始读取
        return read()
        })
        .catch((error) => {
          console.error('Error:', error);
        })
  • 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
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号