JavaScript连接SSE服务
2023年10月5日
背景
需要在前端通过js连接服务端的sse服务,并在连接时发送请求报文。以及获得响应结果
依赖项
使用到第三方组件:@fortaine/fetch-event-source 需要先使用npm i @fortaine/fetch-event-source 命令安装
使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import {EventStreamContentType, fetchEventSource} from '@fortaine/fetch-event-source'; const requestTimeoutId = setTimeout( () => ctrl.abort(), 30 * 1000, ); let isFinish = false fetchEventSource(`${env.baseURL}/v1/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, // 这里的data属性不能太大,底层使用的是get url参数传递 body: JSON.stringify(data), signal: ctrl.signal, async onopen(response) { clearTimeout(requestTimeoutId); state.input = "" const contentType = response.headers.get("content-type"); if (response.ok && contentType.startsWith(EventStreamContentType)) { return; // everything's good } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { // client-side errors are usually non-retriable: console.log(response) } else { console.log(response) } if (contentType?.startsWith("text/plain")) { const responseText = await response.clone().text(); console.log(responseText) } stopWriting() }, onmessage(msg) { // console.log("msg", msg) const text = msg.data; try { const json = JSON.parse(text); } catch (e) { console.error("[Request] parse error", text, msg); } }, onclose() { // 如果当前输出结果未完成,通过抛出异常,继续执行 }, onerror(err) { console.log("error", err) }); |