一、使用EventSOurce
EventSource
接口是 web 内容与服务器发送事件通信的接口。
const evtSource = new EventSource("服务器地址");
evtSource.onopen = (e) => {
console.log('建立链接',e)
};
evtSource.onmessage = (e) => {
console.log('接收消息',e)
};
evtSource.onerror= (error) => {
console.log('错误信息',error)
};
二、 使用@microsoft/fetch-event-source
1、安装
npm i @microsoft/fetch-event-source
2、使用
import { fetchEventSource } from '@microsoft/fetch-event-source';
const url = ref('/getMsg');
class RetriableError extends Error {}
class FatalError extends Error {}
const abortController = ref();
const eventSource = ref();
abortController.value = new AbortController();
const initFetchEventSource = (url) => {
eventSource.value = fetchEventSource(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
signal: abortController.value.signal,
asynconopen() {
if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
return; // everything's good
} else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
// client-side errors are usually non-retriable:
throw new FatalError();
} else {
throw new RetriableError();
}
},
onmessage(msg) {
// if the server emits an error message, throw an exception
// so it gets handled by the onerror callback below:
// console.log('接收消息', msg);
if (msg.event === 'FatalError') {
throw new FatalError(msg.data);
}
if (msg.data.includes('DONE')) {
abortController.value.abort(); // 结束会话
} else {
let res = JSON.parse(msg.data);
console.log('接收消息',res)
}
},
onclose() {
console.log('关闭链接')
abortController.value.abort(); // 结束会话
},
onerror(err) {
console.log('抛出异常', err);
abortController.value.abort(); // 结束会话
}
});