前端如何接收SSE流式数据传输(大模型网站常用)
使用fetchEventSource
参考:https://blog.csdn.net/qq_43750656/article/details/131591198
https://zhuanlan.zhihu.com/p/686618062
首先安装:
npm install --save @microsoft/fetch-event-source
我参考各个资料写的函数:
// 流式传输处理函数 export function sseRequest(url: string, data: object, successCallback: Function, closeCallback?: Function, errCallback?: Function) { const abortController = new AbortController() fetchEventSource(import.meta.env.VITE_APP_BASE_API + url, { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8', 'Accept': '*/*', 'token': localStorage.getItem('token')! }, body: JSON.stringify(data), openWhenHidden: true, // 取消visibilityChange事件 signal: abortController.signal, // AbortSignal // 按需添加此函数,不用就不添加 async onopen(response) { if (response.ok && response.headers.get('content-type') === EventStreamContentType) { return; // everything's good } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { // client-side errors are usually non-retriable: throw new FatalError(); } else { throw new RetriableError(); } }, onmessage(ev) { // 每当消息推送过来时,就调用处理函数处理消息 successCallback(ev) }, onerror(err) { abortController.abort() if (errCallback) { errCallback(err) } throw err }, onclose() { abortController.abort() if (closeCallback) { closeCallback() } } }) } // 调用sseRequest示例: export const beginWrite = (topic: string, styleId: string, style: string) => { const writeStore = useWriteStore() function successCallback(ev: { data: string, event: string, id: string, retry: number }) { if (ev.event === 'message') { const newStr = ev.data.replace(/_::_/g, '\n\n').replace(/_:_/g, '\n').replace(/_._/g, ' ') writeStore.sseInput += newStr } if (ev.event === 'message_end') { writeStore.sseInput = '' } } sseRequest('/knowledge/know_write', { topic, styleId, style }, successCallback) }
漫思