vue3+ts前端封装EventSource并在请求头添加token的方法
作者:全能全知者
这篇文章主要介绍了vue3+ts前端封装EventSource并在请求头添加token,本文将介绍如何使用 event-source-polyfill 来解决这个问题,需要的朋友可以参考下
vue3+ts前端封装 EventSource 并在请求头添加 token
背景介绍
在前端开发中,我们经常需要使用 Server-Sent Events (SSE) 来实现服务器向客户端推送数据。但原生的 EventSource 不支持在请求头中添加自定义字段,这使得我们无法添加 token 等认证信息。本文将介绍如何使用 event-source-polyfill 来解决这个问题。
环境准备
首先需要安装 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
}
// 创建 SSE 连接
function createSSEConnection(url: string, options?: SSEOptions) {
// 从 store 中获取 token
const token = (store.state as StateAll).user.token
// 创建 EventSource 实例,添加 token
const eventSource = new EventSourcePolyfill(BASE_URL + url, {
headers: {
'Authorization': token
}
})
// 连接成功回调
eventSource.addEventListener('open', () => {
console.log('SSE连接成功')
options?.onOpen?.()
})
// 接收消息回调
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,支持添加自定义请求头
- 在创建连接时从 store 中获取 token 并添加到请求头
- 处理连接成功、接收消息、错误等事件
- 提供关闭连接的方法,在组件销毁时调用
- 对 token 失效等特殊错误进行处理
注意事项
- 确保后端支持 SSE 连接并正确处理 token
- 注意在组件销毁时及时关闭连接,避免内存泄漏
- 建议对接收到的消息做 try-catch 处理,避免解析失败导致程序崩溃
- 可以根据实际需求扩展更多的事件处理和错误处理逻辑
通过以上封装,我们就可以在前端优雅地使用带有 token 认证的 SSE 连接了。这种方式既保证了安全性,又提供了良好的开发体验。
到此这篇关于vue3+ts前端封装EventSource并在请求头添加token的文章就介绍到这了,更多相关vue请求头添加token内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
