vue实现智能问答助手sse流式请求案例

使用fetchEventSource内置api,而不是Ajax请求,响应类似于打字机一样,只能在浏览器上使用,小程序不支持;

一、下载 @microsoft/fetch-event-source

npm install @microsoft/fetch-event-source

二、项目引用

import { fetchEventSource } from "@microsoft/fetch-event-source";

三、中断会话

const ctrl = new AbortController(); // 用于中断请求 

代码

  const ctrl = new AbortController(); // 用于中断请求 
  fetchEventSource('api地址', {  
        headers: {
          "Content-Type": "application/json",
          Accept: ["text/event-stream", "application/json"],
        },
        body: JSON.stringify({
          
        }),
        method: 'POST', 
        signal: ctrl.signal,  
        openWhenHidden: true, // 页面退至后台时保持连接  
        onopen: (response) => {  
           console.log('打开连接')
        },
        onmessage: (event) => { 
          console.log('收到信息',event)
        },  
        onerror: (error) => {  
            ctrl.abort(); // 中断请求  
        },  
      })
posted @   梧桐树211  阅读(355)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示
主题色彩