sse 长链接,window中有一个叫EventSource
的构造函数。一个EventSource
实例会对服务器开启一个持久化的连接,以text/event-stream
格式发送事件,此连接会一直保持开启直到通过调用EventSource.close()
关闭。但使用EventSource
时只能把参数加到url
后面,而且也不能像fetch
请求那样设置header
等参数。借助fetch-event-source
这个库就可以像发起fetch
请求一样发起服务器单向通信请求。
它声明了fetchEventSource
的第2个参数的类型。参数一共有7个。headers
请求头。
onopen 连接建立时的回调函数,如果没有设置会调用默认的defaultOnOpen
,这个默认回调里进行了返回值类型判断。onmessage
每次收到消息时的回调函数,参数是消息对象,它的类型就是parse.ts
中定义的EventSourceMessage
。
onclose 连接关闭时的回调函数。
onerror连接发送错误时的回调函数,如果没有指定这个回调或返回undefined
就会发起重新连接请求。
openWhenHidden 默认为false
,监听visibilitychange
,当页面不可见时关闭连接,当页面重新可见时重新打开连接。
let ctrlAbout = new AbortController()
let eventSourcepost = fetchEventSource(
你的url,
{
method: 'post',
headers: {
t: getCookie('t'),
satoken: getCookie('satoken'),
'Content-Type': 'application/json'
},
signal: ctrlAbout.signal,
body: JSON.stringify(data),
openWhenHidden: true,//默认为false,监听visibilitychange,当页面不可见时关闭连接,当页面重新可见时重新打开连接。
onmessage(event) {
// 成功之后操作
console.log("成功之后操作")
},
onerror() {
console.log(11)
// 服务异常
},
onclose() {
// 服务关闭
}
}
)