vue3+ts前端封裝EventSource并在請求頭添加token的方法
vue3+ts前端封裝 EventSource 并在請求頭添加 token
背景介紹
在前端開發(fā)中,我們經(jīng)常需要使用 Server-Sent Events (SSE) 來實現(xiàn)服務器向客戶端推送數(shù)據(jù)。但原生的 EventSource 不支持在請求頭中添加自定義字段,這使得我們無法添加 token 等認證信息。本文將介紹如何使用 event-source-polyfill
來解決這個問題。
環(huán)境準備
首先需要安裝 event-source-polyfill
依賴:
npm install event-source-polyfill # 或 yarn add event-source-polyfill # 或 pnpm install event-source-polyfill
如果是ts項目,同時還需要安裝對應的類型聲明文件:
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 實例,添加 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?.([]) } }) // 錯誤處理 eventSource.addEventListener('error', (error: any) => { console.error('SSE連接錯誤:', 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('消息連接錯誤:', error) } }) // 組件銷毀時關閉連接 onUnmounted(() => { sseConnection?.close() })
關鍵點說明
使用 event-source-polyfill
替代原生 EventSource,支持添加自定義請求頭
- 在創(chuàng)建連接時從 store 中獲取 token 并添加到請求頭
- 處理連接成功、接收消息、錯誤等事件
- 提供關閉連接的方法,在組件銷毀時調(diào)用
- 對 token 失效等特殊錯誤進行處理
注意事項
- 確保后端支持 SSE 連接并正確處理 token
- 注意在組件銷毀時及時關閉連接,避免內(nèi)存泄漏
- 建議對接收到的消息做 try-catch 處理,避免解析失敗導致程序崩潰
- 可以根據(jù)實際需求擴展更多的事件處理和錯誤處理邏輯
通過以上封裝,我們就可以在前端優(yōu)雅地使用帶有 token 認證的 SSE 連接了。這種方式既保證了安全性,又提供了良好的開發(fā)體驗。
到此這篇關于vue3+ts前端封裝EventSource并在請求頭添加token的文章就介紹到這了,更多相關vue請求頭添加token內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue cli3 庫模式搭建組件庫并發(fā)布到 npm的流程
這篇文章主要介紹了Vue cli3 庫模式搭建組件庫并發(fā)布到 npm,以下一個簡單的顏色選擇器插件 vColorPicker 講述從開發(fā)到上線到npm的流程,需要的朋友可以參考下2018-10-10vue項目中圖片選擇路徑位置static或assets的區(qū)別及說明
這篇文章主要介紹了vue項目中圖片選擇路徑位置static或assets的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09淺析Vue中Virtual?DOM和Diff原理及實現(xiàn)
這篇文章主要為大家詳細介紹了Vue中Virtual?DOM和Diff原理及實現(xiàn)的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-03-03vue-cli 引入jQuery,Bootstrap,popper的方法
這篇文章主要介紹了vue-cli 引入jQuery,Bootstrap,popper的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09