如何使用fetchEventSource實現(xiàn)sse流式請求
更新時間:2024年08月30日 08:40:58 作者:寫代碼的拉克絲
這篇文章主要介紹了如何使用fetchEventSource實現(xiàn)sse流式請求問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
使用fetchEventSource實現(xiàn)sse流式請求
最近在項目開發(fā)的過程中,需要實現(xiàn)一個功能
根據(jù)進度條的進度動態(tài)實時加載獲取到的數(shù)據(jù)并展示出來

用到的是fetchEventSource
以下主要寫下js的實現(xiàn)的過程(前端用到的ui組件是antd-design-vue1.78版本 vue2.0項目)
首先下載插件:
npm install --save @microsoft/fetch-event-source
<div class="progress_container" v-if="!progressDone">
<div class="progress_row">
<a-progress type="line" :percent="progressValue" status="active" />
</div>
<div class="progress_text">
{{ progressTxt }}
</div>
</div>
<script>
import { fetchEventSource } from '@microsoft/fetch-event-source'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
data () {
return {
speed: 30,
progressValue: 0,//進度條初始值
progressTxt: '',//進度條文字展示默認值
eventSource: null,
abortController: null,
checkMessage: [],
checkResult: {},
resultData: [],
submitUnable: true,
progressDone: false
}
},
created () {
this.connectSSE()
},
destroyed () {
this.stopSSE()
},
methods: {
connectSSE () {
this.abortController = new AbortController() // 終止or結(jié)束會話,做了個全局的...
const url = process.env.VUE_APP_API_BASE_URL + `自己的請求數(shù)據(jù)接口`
const token = storage.get(ACCESS_TOKEN)
// 開始會話鏈接,也做了個全局的......
this.eventSource = fetchEventSource(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
[ACCESS_TOKEN]: token
},
// 傳參只能發(fā)送文本格式的數(shù)據(jù)
body: JSON.stringify({
}),
signal: this.abortController.signal,
onopen: (event) => {
console.log(event, 'SSE在連接打開時被調(diào)用')
},
onmessage: (event) => {
// console.log('SSE會在通過事件源收到數(shù)據(jù)時觸發(fā)')
// console.log('接口返回', JSON.parse(event.data))
//我這里是判斷我請求回來的數(shù)據(jù)里是否包含'[DONE]',他是數(shù)組里的最后一項,表示加載完成
if (!event.data.includes('[DONE]')) {
const data = JSON.parse(event.data)
const text = data.message
const percent = data.percent
const message = data.message
if (text === 'connect') {
// 連接成功,開始檢測邏輯
this.progressDone = false
this.progressValue = 0
this.progressTxt = '數(shù)據(jù)檢查中,該過程可能需要一段時間,請勿關(guān)閉窗口'
this.getTurnCheck()
return false
}
//定時器,控制進度條和文字的展示速度
this.speed += 300
this.timer = setTimeout(() => {
this.progressValue = Number(percent)
this.progressTxt = message
if (this.progressValue === 100 && !this.progressDone) {
this.stopSSE()
}
}, this.speed)
}
if (event.data.includes('[DONE]')) {
}
},
onerror: () => {
console.log('SSE拋出異常onerror')
this.stopSSE()
},
// onclose函數(shù)是會話結(jié)束正常關(guān)閉觸發(fā),但幾乎沒有做到這步,不執(zhí)行這個回調(diào),不知道什么原因
onclose: () => {
console.log('onclose')
}
})
},
// 停止SSE
async stopSSE () {
// 關(guān)閉業(yè)務(wù),執(zhí)行關(guān)閉sse數(shù)據(jù)接口
await this.getCloseSse()
if (this.abortController) {
this.timer && clearTimeout(this.timer)
console.log('SSE結(jié)束會話了')
this.abortController.abort() // 結(jié)束會話
}
},
//檢查數(shù)據(jù)的接口
async getTurnCheck () {
const params = {
}
},
//關(guān)閉sse接口
async getCloseSse () {
const params = {
}
const [err, res] = await to(closeSse(params))
if (err) return false
}
},
}
</script>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
vue如何封裝自己的Svg圖標(biāo)組件庫(svg-sprite-loader)
這篇文章主要介紹了vue如何封裝自己的Svg圖標(biāo)組件庫(svg-sprite-loader),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
vue3中使用VueParticles實現(xiàn)粒子動態(tài)背景效果
為了提高頁面展示效果,特別類似于登錄界面內(nèi)容比較單一的,粒子效果作為背景經(jīng)常使用到,vue工程中利用vue-particles可以很簡單的實現(xiàn)頁面的粒子背景效果,本文給大家分享vue粒子動態(tài)背景效果實現(xiàn)代碼,需要的朋友參考下吧2022-05-05
vue配置代理vue.config.js后不生效的解決(小坑)
這篇文章主要介紹了vue配置代理vue.config.js后不生效的解決(小坑),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
vue3 element-plus二次封裝組件系列之伸縮菜單制作
這篇文章主要介紹了vue3 element-plus二次封裝組件系列之伸縮菜單制作,是基于vue3 vite element-plus搭建的,值的注意的時候,里面的圖標(biāo)組件是經(jīng)過處理的,結(jié)合實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01

