前端获取SSE流式数据推送

123 阅读1分钟
使用 EventSource
var source = new EventSource("http://localhost:9001/ai", {
    withCredentials: true,
});

source.onopen = function () {
    console.log('连接已经建立')
};
source.onmessage = function (event) {
    let values = JSON.parse(event.data) 
    console.log(values)
    if (values.is_end === true) {
        source.close()
    }
};
source.onerror = function () {
    console.log('服务关闭')
};
  1. 需要后端标记消息推送是否已经结束,前端需要手动关闭连接()
  2. 无法带入更多标记信息,如token等信息
使用 fetch
 fetch('http://localhost:9001/ai')
    .then((response) => response.body)
    .then((rb) => {
    const reader = rb.getReader();

    return new ReadableStream({
        start(controller) {
            function push() {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        controller.close();
                        return;
                    }
                    new Response(value, { headers: { "Content-Type": "text/html" } }).text().then(value => {
                        let results = value.replace(/data: /g, "").split("\n").filter(Boolean);
                        let objects = results.map(str => JSON.parse(str));
                        objects.forEach(item => {
                            text_dom.innerText += item.result
                        })
                    })
                    push();
                });
            }
            push();
        },
    });
})
  1. 获取数据有点麻烦
  2. 没有自动重连机制
  3. 会出现多个流,输出在一起