vue流式接口的使用解读(EventSource)
更新时间:2025年12月16日 15:23:27 作者:qq_50949240
文章主要介绍了如何使用EventSource和WebSocket进行流式请求,以及如何主动关闭流式请求连接,同时,文章还提到了流式接口的要求,包括携带请求头的方法
一、EventSource
1.如果接口地址是http协议的,使用EventSource。如果是ws的,使用webSocket
2.主动关闭流式请求连接的方式:source.close()
3.参考链接:Websocket的用法及常见应用场景
if (!!window.EventSource) {
// 建立连接
let source = new EventSource(window.config.baseURL + '/tsyp/stream?uuid=' + uuid);
//连接一旦建立,就会触发open事件
source.onopen = function (event) {
}
//客户端收到服务器发来的数据
source.onmessage = function (event) {
let data = event.data
if (data == "AIQA_EOF") {
source.close() //关闭请求的连接
}
}
//如果发生通信错误(比如连接中断),就会触发error事件
source.onerror = function (event) {
console.error('EventSource failed:', event);
}
} else {
console.warn("你的浏览器不支持SSE");
}二、流式接口要求携带请求头
1.可以使用封装的EventSourcePolyfill。(此方法只能用get请求)
但注意:
EventSourcePolyfill发送的请求可以携带请求头,但是只能是get请求
async putQuestion(query) {
let that = this
// 建立连接
let source = new EventSourcePolyfill(`/eventSourceFill/chat/conversation/stream`,
{
withCredentials: true,
headers: {
"Content-Type": "application/json",
Authorization: 'Bearer ' + getToken(),
connection: "keep-alive",
}
});
//连接一旦建立,就会触发open事件
source.onopen = function (event) {
source.send('Authorization: Bearer ' + getToken());
console.log("连接建立成功")
}
//客户端收到服务器发来的数据
source.onmessage = function (event) {
let data = event.data
console.log("data:", data)
if (data == "AIQA_EOF") {
source.close()
} else {
}
}
//如果发生通信错误(比如连接中断),就会触发error事件
source.onerror = function (event) {
console.error('EventSource failed:', event);
}
},2.请求要求携带请求头(post、get请求均可)
async sendRequest(query) {
let controller = new AbortController();
let {signal} = controller;
//controller.abort() 用于取消fetch接口请求
this.cancel_QA = controller
//使用fetch发送请求
const response = await fetch('http://****/chat/conversation/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + getToken()
},
body: JSON.stringify(query),
signal
});
// 检查响应是否成功
if (!response.ok) {
console.error('网络响应失败:', response.statusText);
return;
}
// 获取响应体的可读流
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
// 逐块读取数据
while (true) {
const {done, value} = await reader.read();
if (done) break; // 流结束
let msg = decoder.decode(value, {stream: true})
if (msg.includes("LLM-EOF")) {
console.warn("回答结束")
this.cancel_QA = null
} else {
}
}
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue3.0使用mapState,mapGetters和mapActions的方式
这篇文章主要介绍了vue3.0使用mapState,mapGetters和mapActions的方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-06-06
element-ui tree 手动展开功能实现(异步树也可以)
这篇文章主要介绍了element-ui tree 手动进行展开(异步树也可以),项目中用到了vue的element-ui框架,用到了el-tree组件,需要的朋友可以参考下2022-08-08
Vue v-for中的 input 或 select的值发生改变时触发事件操作
这篇文章主要介绍了Vue v-for中的 input 或 select的值发生改变时触发事件操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08
vue上传项目到git时,如何忽略node_modules文件夹
这篇文章主要介绍了vue上传项目到git时,如何忽略node_modules文件夹,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-09-09


最新评论