Vue中使用eventSource处理ChatGPT聊天SSE长连接获取数据
- 先安装event-source-polyfill插件 【npm install event-source-polyfill】
- 使用插件EventSourcePolyfill创建eventSource
- 打开eventSource开关 【eventSource.onopen】
- 获取消息数据流做处理,这里数据流完了之后记得关闭 eventSource【eventSource.onmessage】
- eventSource错误处理 【eventSource.onerror】
// 创建sse const eventSource = new EventSourcePolyfill("/api/chatApi/createSse", { headers: { authorization: "Bearer" + " " + (localStorage.getItem("loginObj") && JSON.parse(localStorage.getItem("loginObj")).token), }, }); eventSource.onopen = (event) => { // console.log("开始输出后端返回值", event.target); sse = event.target; }; eventSource.onmessage = (event) => { let wordTimeout = null; // console.log("event-data====》", event.data); // 返回结束标识关闭sse if (event.data == "[DONE]") { // this.itemMessageList.push(obj); wordTimeout = null; if (sse) { sse.close(); } return; } if (!event.data.indexOf("<br /><br />") == 0) { let __data = JSON.parse(event.data); console.log("__data-data========>", __data); // console.log(obj, "-----------obj"); if ((__data && __data.content == null) || __data.content == "null") { return; } if ( this.itemMessageList[this.itemMessageList.length - 1].content == "思考中..." ) { this.itemMessageList[this.itemMessageList.length - 1].content = ""; } wordTimeout = setTimeout(() => { this.itemMessageList[this.itemMessageList.length - 1].content += __data.content.replace(/\n/g, "<br />"); //找到\n并替换成换行标签<br /> }, 10); } }; eventSource.onerror = (event) => { this.eleui.message("服务异常请重试并联系开发者"); event.target.close(); };