前几天做了一个项目,需要用到SSE(Server-Send Events)技术,在前端中,我们一般是通过EventSource来实时接收后端传来的数据。
EventSource建立连接非常简单,直接通过其构造函数即可。
const eventSource = new EventSource(url);
监听服务器发送的数据:
eventSource.onmessage = function (event) {
console.log(event.data);
};
常理说就能读取服务器中的数据了,不过我在做项目时用该方法迟迟没有读取到服务器传过来的数据,而且在本地浏览器中是可以读取数据的,困扰了很长时间,然后向大佬请教,大佬直接发我他写的使用Fetch替换EventSource的方法,拿着代码稍微改造了一下,成功读取数据,给大家分享一波。
async function myEventSource(url) {
const resp = await fetch(url);
if (resp.ok) {
const reader = resp.body.getReader();
let accumulatedData = ''; // 用于累积数据
while (SSE.value) { // SSE.value设置成true,并在组件生命周期调用销毁的钩子时设置为false
const { value, done } = await reader.read();
if (done) {
break;
}
accumulatedData += new TextDecoder().decode(value);
// 检查是否完整接收了一条 SSE 事件数据, 如果不是完整的数据, 就要返回循环, 继续读取数据
if (accumulatedData.includes('\n\n')) {
try {
const currentInfo = JSON.parse(eventData).data.data; // 将数据转换成JSON格式
} catch (error) {
console.log(error);
}
accumulatedData = remainingData; // 处理完一条数据后,将剩余数据留作下一次拼接
}
}
}
}