306 字
2 分钟
使用post请求建立长连接实现sse
  • 最近遇到一个chatGPT的相关功能,需要做成文字一个个弹出的功能,如果使用普通的http请求会一次性得到结果,如果后台计算时间太长还可能会导致超时,影响用户体验。
  • 所以使用长连接SSE(Server Sent Event),直译为服务器发送事件,顾名思义,也就是客户端可以获取到服务器发送的事件。我们常见的 http 交互方式是客户端发起请求,服务端响应,然后一次请求完毕;但是在 sse 的场景下,客户端发起请求,连接一直保持,服务端有数据就可以返回数据给客户端,这个返回可以是多次间隔的方式。
  • 但是问题是原生的EventSource 不能使用post方法,只能使用get方法,而且还不能自定义请求header,所以我们可以使用npm包:@microsoft/fetch-event-source
Terminal window
npm i @microsoft/fetch-event-source
import {fetchEventSource} from '@microsoft/fetch-event-source';
const controller = new AbortController()
const signal = controller.signal
fetchEventSource('请求的url', {
method: 'POST',
signal: signal,
headers: {
/* 请求头配置 */
},
body: JSON.stringify({
/* 发送的内容 */
}),
onmessage(msg) {
let result= JSON.parse(msg.data); // 得到的数据
},
onerror(err){
// 必须抛出错误才会停止
throw err
}
})
使用post请求建立长连接实现sse
https://blog.amlx.top/posts/post/
作者
Amlx.
发布于
2025-03-13
许可协议
CC BY-NC-SA 4.0