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);

});

相关推荐
流烟默7 小时前
SSE 实战:在 SpringBoot + Vue 项目中零依赖实现轻量级实时消息推送
vue.js·spring boot·后端·sse
执子念的飞鱼7 小时前
纯前端预览 275 种文件格式是怎么做到的
前端·vue.js·react.js
vx_Biye_Design10 小时前
PHP中医养生馆预约系统60841-计算机课程设计、毕业设计
vue.js·spring boot·后端·mysql·php·课程设计·express
gc_229919 小时前
Vue框架学习(1:环境搭建)
vue.js
我的div丢了肿么办1 天前
element-plus表格使用:filter-method过滤导致出现无数据
前端·javascript·vue.js
贾公子1 天前
AI 内容检测 API 接入实战——异步任务、幂等键与轮询的正确写法
vue.js
星光不问赶路人1 天前
Vue 项目类型检查:深入理解 vue-tsc --build
前端·vue.js
WeiXin_DZbishe1 天前
基于springboot装修风格选择系统的设计与开发-计算机毕设【课程设计】77964
java·vue.js·spring boot·后端·python·php·课程设计
雪碧聊技术1 天前
Vue 一个页面中使用多个同类组件出现“串数据“现象?一个 key 就能解决
vue.js·v-show·一个页面使用多个相同组件·解决数据错乱·v-if、key
Java小卷1 天前
Vue3 动态表单支持弹框组件
前端·vue.js·低代码