一、安装
npm i @fortaine/fetch-event-source -S
二、引入
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
const chatPayload = {
method: "POST",
body: JSON.stringify({
...requestPayload,
}),
headers,
};
fetchEventSource('/chat/v1', {
...chatPayload,
async onopen(res) {
const contentType = res.headers.get("content-type");
console.log("[Request] response content type: ", contentType);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
}
},
onmessage(msg) {
const text = msg.data;
},
onclose() {
},
onerror(e) {
},
openWhenHidden: true,
});
}