前端調(diào)用SSE接口
使用js的EventSource API
const source = new EventSource('/sse);
source.onmessage = function(event) {
? const data = JSON.parse(event.data);
? // 結(jié)束標(biāo)識
? if(data == '__stop__') {
? ? source.close();
? ? return;
? }
? document.getElementById('events').innerHTML += '<p>${data.message}</p>';
}
source.onerror = function(error) {
? console.error('Error occurred:', error);
? source.close();
}
使用fetchEventSource 插件
npm install --save @microsoft/fetch-event-source
import {fetchEventSource} from '@microsoft/fetch-event-source';
send() {
? const params = {
? ? 'prompt': ''
? };
? const vm = this;
? const ctrlAbout = new window.AbortController();
? const {signal} = ctrlAbout;
? fetchEventSource(Url, {
? ? method: 'POST',
? ? headers: {
? ? ? 'Content-Type': 'application/json',
? ? ? 'Accept': 'text/event-stream',
? ? ? 'X-Requested-With': 'XMLHttpRequest'
? ? },
? ? body: JSON.stringify(params),
? ? signal: ctrlAbout.signal, // AbortSignal
? ? openWhenHidden: true, // 去u u喜愛哦visibilityCHange事件
? ? onmessage(event){
? ? ? console.loginfo(event.data);
? ? ? //在這里操作流式數(shù)據(jù)
? ? ? const message = JSON.parse(event.data);
? ? ? vm.content += message.data;
? ? ? // 保證打字輸入時滾動條在最下方
? ? ? vm.$nextTick(() => {
? ? ? ? const contentEl = vm.$refs.content.$el;
? ? ? ? contentEl.scrollTop = contentEl.scrollHeight - contentEl.clientHeight;
? ? ? })
? ? },
? ? onclose(e) {
? ? ? //關(guān)閉流
? ? ? //中斷流式返回
? ? ? ctrl.abort();
? ? },
? ? onerror(error){
? ? ? // 返回流報錯
? ? ? console.info(error);
? ? ? // 中斷流式返回
? ? ? ctrl.abort();
? ? ? //直接拋出錯誤,避免反復(fù)調(diào)用
? ? ? throw err;
? ? }
? })
}