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

});

相关推荐
计算机毕设定制辅导-无忧学长1 小时前
《基于Spring Boot的迷游哈游戏综合服务平台的开发》
java·vue.js·spring boot·mysql·迷游哈游戏综合服务平台
非优秀程序员11 小时前
第04章 邮箱大战,163 与 QQ 的暗战|《互联网产品恩仇录》
java·vue.js·架构
tryCbest17 小时前
Vue系列——第 15 篇:内置组件全家桶——Transition、Teleport、Suspense、KeepAlive
前端·vue.js
徐小夕1 天前
开源Vector-Graph-RAG:向量+图谱双引擎,打破纯向量RAG的效果天花板
前端·vue.js·github
FungLeo1 天前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
FungLeo1 天前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
软件技术NINI2 天前
基于SpringBoot和Vue的新能源汽车销售推荐系统
java·vue.js·spring boot·后端·汽车·毕业设计·毕设
招风的黑耳2 天前
SpringBoot+Vue+MySQL 民宿在线预定平台 完整可运行版(源码+文档)
vue.js·spring boot·mysql
10share3 天前
基于大模型的 i18n 方案:把中文原文当 Key,轻松搞定多语言维护
前端·vue.js
啾咪orJIUMI3 天前
Vue 3 + 高德地图封装实战:点位、区域、Loca 流光与 Vue 信息窗体
前端·vue.js