前端如何接收EventStream中的数据?
本文目录
- 1、fetch
- 2、EventSource
fetch
fetch是浏览器内置的方法无需下载
fetch("http://127.0.0.1:6594/ws/getAccessToken", {
method: "get",
})
.then((response) => {
const decoder = new TextDecoder("utf-8");
let buffer = [];
const reader = response.body.getReader();
function read() {
reader.read().then(function processText({ done, value }) {
if (done) {
return buffer;
}
const chunk = decoder.decode(value, { stream: false });
buffer.push(buffer)
console.log(chunk);
read();
});
}
return read();
})
.then((result) => {
console.log(result);
})
.catch((error) => console.log("error", error));
发送请求后浏览器显示的效果
可以接收到了!
EventSource
EventSource 是用于接收服务器端发送的服务器推送事件(Server-Sent Events,SSE)的接口。它允许客户端从服务器端获取实时更新,是一种基于 HTTP 的单向通信机制。
const es = new EventSource("http://127.0.0.1:6594/ws/getAccessToken");
es.onmessage = function (e) {
console.log(e.data);
setTimeout(()=>{
es.close() //4秒后关闭服务器的推送
},4000)
};
接收到了!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」