小工具知识网

当前位置: 首页 > 行业知识 > 【JS】获取接口返回 EventStream 结构的数据(即接收读取 stream 流)

行业知识

【JS】获取接口返回 EventStream 结构的数据(即接收读取 stream 流)

2026-11-11 08:35:09 来源:互联网转载

文章目录

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);        })
    • 上文中用到的parseMultiJson函数:函数链接

上一篇:微信表白墙操作秘籍,轻松掌握神器,表白从此不再难!

下一篇:怎么让服务器加密?