vue实现post请求接口流式输出数据sse

使用fetchEventSource

参考git源码:https://github.com/Azure/fetch-event-source/tree/main

本地联通 发现数据并没有流式输出:vue代理需要关闭compress

如下:

javascript 复制代码
devServer:{

     proxy:{},

     compress:false 

}

安装插件

javascript 复制代码
npm install @microsoft/fetch-event-source

引入插件

javascript 复制代码
import { fetchEventSource } from "@microsoft/fetch-event-source";

vue关键代码:

javascript 复制代码
connectSse(){
      const ctrl = new AbortController();
      fetchEventSource('/api/v1/sse',{
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({data:[this.searchData]}),
        signal: ctrl.signal,
        onopen(response){
          // 成功连接时回调
          console.log('连接成功',response)
        },
        onmessage(msg) {
          // 服务器返回消息回调 返回{ data,event,id,retry } ,data即服务器返回数据


          if (msg.event == '') {
            // 进行连接正常的操作流程
            let result = JSON.parse(msg.data)
            // 将需要展示的数据更新到vue的data中,当然如下this.showData肯定赋值不上,需要将this 指向一个变量,用变量接受数据即可,以下只是展示
            this.showData += result.content
          }

          if (msg.event === 'close') {
            ctrl.abort()
          }
        },
        onerror(err) {
          throw new err()
        }
      })
    },

研发阶段 需要配置nginx

相关推荐
辛-夷10 分钟前
TS封装axios
前端·vue.js·typescript·vue·axios
Swift社区23 分钟前
Vue Router 越写越乱,如何架构设计?
前端·javascript·vue.js
程序员小易1 小时前
前端轮子(1)--前端部署后-判断页面是否为最新
前端·vue.js·node.js
dly_blog2 小时前
Vite 原理与 Vue 项目实践
前端·javascript·vue.js
计算机毕设VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue汽车销售系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·汽车·课程设计
ttod_qzstudio3 小时前
DriveLerpControllerEditor开发总结:一个3D编辑器插值控制系统的实现
vue.js·typescript·编辑器·tdesign
咸鱼加辣3 小时前
【前端框架】路由配置
javascript·vue.js·前端框架
San30.3 小时前
从 0 到 1 打造 AI 冰球运动员:Coze 工作流与 Vue3 的深度实战
前端·vue.js·人工智能
安_3 小时前
为什么 Vue 要用 npm run dev 启动
前端·vue.js·npm
六便士的理想3 小时前
el-table实现滑窗列
前端·vue.js