vue3+ts前端封裝EventSource并在請(qǐng)求頭添加token的方法
vue3+ts前端封裝 EventSource 并在請(qǐng)求頭添加 token
背景介紹
在前端開發(fā)中,我們經(jīng)常需要使用 Server-Sent Events (SSE) 來實(shí)現(xiàn)服務(wù)器向客戶端推送數(shù)據(jù)。但原生的 EventSource 不支持在請(qǐng)求頭中添加自定義字段,這使得我們無法添加 token 等認(rèn)證信息。本文將介紹如何使用 event-source-polyfill 來解決這個(gè)問題。
環(huán)境準(zhǔn)備
首先需要安裝 event-source-polyfill 依賴:
npm install event-source-polyfill # 或 yarn add event-source-polyfill # 或 pnpm install event-source-polyfill
如果是ts項(xiàng)目,同時(shí)還需要安裝對(duì)應(yīng)的類型聲明文件:
npm install @types/event-source-polyfill -D # 或 yarn add @types/event-source-polyfill -D # 或 pnpm install @types/event-source-polyfill -D
封裝 SSE 連接方法
在 http 工具類中,我們可以這樣封裝 SSE 連接:
http.ts
import { EventSourcePolyfill } from 'event-source-polyfill'
import store from '@/store'
import type { StateAll } from '@/store'
interface SSEOptions {
onMessage?: (data: any) => void
onError?: (error: any) => void
onOpen?: () => void
}
// 創(chuàng)建 SSE 連接
function createSSEConnection(url: string, options?: SSEOptions) {
// 從 store 中獲取 token
const token = (store.state as StateAll).user.token
// 創(chuàng)建 EventSource 實(shí)例,添加 token
const eventSource = new EventSourcePolyfill(BASE_URL + url, {
headers: {
'Authorization': token
}
})
// 連接成功回調(diào)
eventSource.addEventListener('open', () => {
console.log('SSE連接成功')
options?.onOpen?.()
})
// 接收消息回調(diào)
eventSource.addEventListener('message', (event: any) => {
try {
const data = JSON.parse(event.data)
options?.onMessage?.(data)
} catch (error) {
console.error('解析消息失敗:', error)
options?.onMessage?.([])
}
})
// 錯(cuò)誤處理
eventSource.addEventListener('error', (error: any) => {
console.error('SSE連接錯(cuò)誤:', error)
// token 失效處理
if (error?.status === 401) {
store.commit('user/clearToken')
window.location.replace('/login')
return
}
options?.onError?.(error)
})
return {
eventSource,
close: () => {
eventSource.close()
}
}
}使用示例
在組件中使用封裝好的 SSE 連接:
const unreadMessages = ref<ElectricityMessage[]>([])
let sseConnection: { close: () => void } | null = null
// 建立 SSE 連接
sseConnection = http.createSSEConnection('messages/unread', {
onOpen: () => {
console.log('消息連接已建立')
},
onMessage: (data) => {
unreadMessages.value = data
},
onError: (error) => {
console.error('消息連接錯(cuò)誤:', error)
}
})
// 組件銷毀時(shí)關(guān)閉連接
onUnmounted(() => {
sseConnection?.close()
})關(guān)鍵點(diǎn)說明
使用 event-source-polyfill 替代原生 EventSource,支持添加自定義請(qǐng)求頭
- 在創(chuàng)建連接時(shí)從 store 中獲取 token 并添加到請(qǐng)求頭
- 處理連接成功、接收消息、錯(cuò)誤等事件
- 提供關(guān)閉連接的方法,在組件銷毀時(shí)調(diào)用
- 對(duì) token 失效等特殊錯(cuò)誤進(jìn)行處理
注意事項(xiàng)
- 確保后端支持 SSE 連接并正確處理 token
- 注意在組件銷毀時(shí)及時(shí)關(guān)閉連接,避免內(nèi)存泄漏
- 建議對(duì)接收到的消息做 try-catch 處理,避免解析失敗導(dǎo)致程序崩潰
- 可以根據(jù)實(shí)際需求擴(kuò)展更多的事件處理和錯(cuò)誤處理邏輯
通過以上封裝,我們就可以在前端優(yōu)雅地使用帶有 token 認(rèn)證的 SSE 連接了。這種方式既保證了安全性,又提供了良好的開發(fā)體驗(yàn)。
到此這篇關(guān)于vue3+ts前端封裝EventSource并在請(qǐng)求頭添加token的文章就介紹到這了,更多相關(guān)vue請(qǐng)求頭添加token內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3+Three.js實(shí)現(xiàn)為模型添加點(diǎn)擊事件
本文主要介紹了如何在Vue3和Three.js環(huán)境中為模型添加點(diǎn)擊事件監(jiān)聽,具體方法是利用Three.js的Vector2和Raycaster,首先,創(chuàng)建一個(gè)Vector2對(duì)象來獲取鼠標(biāo)位置;然后,創(chuàng)建一個(gè)Raycaster對(duì)象來投射光線2024-10-10
5分鐘學(xué)會(huì)Vue動(dòng)畫效果(小結(jié))
這篇文章主要介紹了5分鐘學(xué)會(huì)Vue動(dòng)畫效果(小結(jié)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07
Element如何實(shí)現(xiàn)loading的方法示例
本文主要介紹了Element如何實(shí)現(xiàn)loading的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Vue.js+Layer表格數(shù)據(jù)綁定與實(shí)現(xiàn)更新的實(shí)例
下面小編就為大家分享一篇Vue.js+Layer表格數(shù)據(jù)綁定與實(shí)現(xiàn)更新的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03
Vue.js實(shí)現(xiàn)輸入框清空功能的兩種方式
Vue.js 是一個(gè)流行的前端框架,它提供了多種方法來實(shí)現(xiàn)數(shù)據(jù)的雙向綁定和事件處理,在構(gòu)建表單時(shí),我們經(jīng)常需要實(shí)現(xiàn)清空輸入框的功能,本文將介紹兩種在Vue中實(shí)現(xiàn)輸入框清空功能的方法,感興趣的小伙伴跟著小編一起來看看吧2024-12-12
Vue3報(bào)錯(cuò)computed?value?is?readonly的解決方案
這篇文章主要為大家詳細(xì)介紹了Vue3報(bào)錯(cuò)computed?value?is?readonly的原因排查和解決方法,文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下2026-03-03
vue實(shí)現(xiàn)點(diǎn)擊展開點(diǎn)擊收起效果
這篇文章主要介紹了vue實(shí)現(xiàn)點(diǎn)擊展開,點(diǎn)擊收起效果,首先我們需要定義data里面的數(shù)據(jù),使用computed對(duì)data進(jìn)行處理,需要的朋友可以參考下2018-04-04

