使用 EventSource
var source = new EventSource("http://localhost:9001/ai", {
withCredentials: true,
});
source.onopen = function () {
console.log('连接已经建立')
};
source.onmessage = function (event) {
let values = JSON.parse(event.data)
console.log(values)
if (values.is_end === true) {
source.close()
}
};
source.onerror = function () {
console.log('服务关闭')
};
- 需要后端标记消息推送是否已经结束,前端需要手动关闭连接()
- 无法带入更多标记信息,如token等信息
使用 fetch
fetch('http://localhost:9001/ai')
.then((response) => response.body)
.then((rb) => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
new Response(value, { headers: { "Content-Type": "text/html" } }).text().then(value => {
let results = value.replace(/data: /g, "").split("\n").filter(Boolean);
let objects = results.map(str => JSON.parse(str));
objects.forEach(item => {
text_dom.innerText += item.result
})
})
push();
});
}
push();
},
});
})
- 获取数据有点麻烦
- 没有自动重连机制
- 会出现多个流,输出在一起