GPT打字机效果—— fetchEventSouce进行sse流式请求

EventStream基本用法

与 WebSocket 不同的是,服务器发送事件是单向的。数据消息只能从服务端到发送到客户端(如用户的浏览器)。这使其成为不需要从客户端往服务器发送消息的情况下的最佳选择。

const evtSource = new EventSource("/api/v1/sse")

// 每次连接开启时调用

evtSource.onopen = function () {

console.log("连接开始启动");

};

// 每次接受数据时调用

evtSource.onmessage = (e) => {

console.log('输入每次接受的数据',e)

};

// 每次连接发生错误时调用

evtSource.onerror = function () {

console.log("连接发生错误");

};

需要注意的是,EventSource是以get方式发送请求,对于post请求原生的EventSource是无法实现的

如何用post的方式进行eventSource请求

常见的是通过@microsoft/fetch-event-source 这个库里的fetchEventSource来实现

import { fetchEventSource } from '@microsoft/fetch-event-source';

这个库封装了一个方法,使得我们可以便捷的通过这个方法直接进行调用

以下是具体的代码

const controller, setController = useState(new AbortController());

const url = 'http:xxx';

fetchEventSource(url, {

method: 'POST',

headers: {

// SYSTEM_PORTAL_TYPE: 'LINGXI_RUNNING',

'Content-Type': 'text/event-stream',

'X-CSRF-TOKEN': '1232123',

// Cookies: 'ZSMART_LOCALE=zh; ',

},

mode: 'cors',

openWhenHidden: true,

credentials: 'include',

signal: controller?.signal,

onmessage: async (event: any) => {

console.log('eventeventeventeventeventevent');

console.log(event);

},

onerror(err: any) {

console.log('err', err);

},

async onopen(response: any) {

if (response.ok) {

console.log('开始建立连接');

}

},

onclose() {

console.log('关闭');

controller?.abort();

setController(new AbortController());

throw new Error();

},

}).catch((err: any) => {

controller?.abort();

setController(new AbortController());

console.log({ err });

throw new Error(err);

});

相关推荐
锋行天下15 小时前
我试图优化 Vite 的拆包,结果首屏慢了 10 倍
前端·vue.js·架构
ZhengEnCi20 小时前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
晴虹21 小时前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js
Forever7_21 小时前
尤雨溪转发:Vue-tui 0.1 发布!Vue 终于杀进终端!
vue.js
dkbnull21 小时前
Vue 虚拟 DOM Diff 算法与 key 机制原理
vue.js
前端切图崽_小郭2 天前
虚拟滚动:静态 vs 动态的核心差异与实现?
vue.js
白鲸开源2 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
卤蛋fg62 天前
vue 甘特图 vxe-gantt 的使用(四):周视图的渲染
vue.js
卤蛋fg62 天前
vue 甘特图 vxe-gantt 的使用(三):月视图的渲染
vue.js
卤蛋fg62 天前
vue 甘特图 vxe-gantt 的使用(一):年视图的渲染
vue.js