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

});

相关推荐
૮・ﻌ・几秒前
Vue2(一):创建实例、插值表达式、Vue响应式特性、Vue指令、指令修饰符、计算属性
前端·javascript·vue.js
半生过往43 分钟前
2025 前端动效实战指南:Vue Bits & React Bits 深度拆解(功能 / 复用 / 高频问题处理)
前端·vue.js·react.js
BumBle1 小时前
使用 SortableJS 实现vue3 + Element Plus 表格拖拽排序
前端·vue.js·element
JA+2 小时前
vue 实时数据表格组件 (stk-table-vue)
前端·javascript·vue.js
似水流年QC3 小时前
Electron 实战|Vue 桌面端开发从入门到上线
vue.js·electron·桌面端
合作小小程序员小小店3 小时前
web网页开发,在线%考试,教资,题库%系统demo,基于vue,html,css,python,flask,随机分配,多角色,前后端分离,mysql数据库
前端·vue.js·后端·前端框架·flask
一枚前端小能手4 小时前
🔄 重学Vue之nextTick和slot - 从底层实现到实战应用的完整指南
前端·javascript·vue.js
一嘴一个橘子5 小时前
vue.js 视频截取为 gif - 2(将截取到的gif 转换为base64 、file)
vue.js
你的电影很有趣6 小时前
lesson73:Vue渐进式框架的进化之路——组合式API、选项式对比与响应式新范式
javascript·vue.js
小张成长计划..6 小时前
VUE工程化开发模式
前端·javascript·vue.js