PeaceSheep's blog PeaceSheep's blog
首页
  • 分类
  • 标签
  • 归档
相关链接
提建议&咨询&赞赏
GitHub (opens new window)

PeaceSheep

以最简洁、易懂的话解决问题
首页
  • 分类
  • 标签
  • 归档
相关链接
提建议&咨询&赞赏
GitHub (opens new window)
  • web

    • element-plus滚动条滚动到底部
    • mac使用docker部署nextcloud-aio并为本地域名添加https支持(未成功)
    • 前端处理POST类型的sse请求
    • 网站域名迁移的百度和谷歌SEO优化
    • 使用腾讯云OSS作为个人网站文件处理的存储库
    • 使用cloudflare-r2搭建webdav
  • 物联网与路由器

  • 操作系统

  • 错误解决

  • 使用技巧

  • 教程
  • web
PeaceSheep
2024-06-29

前端处理POST类型的sse请求

想要编写一个类似于ChatGPT的聊天助手,但是不知道怎么处理SSE请求。问了GPT只给出了用EventSource的方法,但是这个只支持GET请求,由于发送的消息内容可能很长,因此使用了POST请求。为了达到目的,最后只能手写了fetch获取数据后进行处理。

fetch("/api/chat-message/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message: this.newMessage.value,
      }),
    })
      .then((response) => {
        if (response.body === null) {
          throw new Error("Response body is null");
        }
     
        const reader = response.body.getReader();
        return new ReadableStream({
          start(controller) {
            function push() {
              reader.read().then(({ done, value }) => {
                if (done) {
                  controller.close();
                  return;
                }
                const text = new TextDecoder("utf-8").decode(value);
                console.log(text)
                processText(text);
                push();
              });
            }
            push();
          }
        });
      })
      .catch((err) => {
        alert("发送消息失败:" + err.message);
      });
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

主要流程如下:

  1. 使用fetch函数发送http POST请求。
fetch("/api/chat-message/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message: this.newMessage.value,
      }),
    })
1
2
3
4
5
6
7
8
9
  1. 使用一个reader,从body中直接读取原始二进制数据。
 const reader = response.body.getReader();
1
  1. 读取消息
 return new ReadableStream({
          start(controller) {
            function push() {
              reader.read().then(({ done, value }) => {
                if (done) {
                  controller.close();
                  return;
                }
                const text = new TextDecoder("utf-8").decode(value);
                console.log(text)
                processText(text);
                push();
              });
            }
            push();
          }
        });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  1. 在processText函数中处理消息
   function processText(text) {
                const lines = text.split("\n\n");
                lines.forEach(line => {
                    if (line.startsWith("data: ")) {
                        const resp = JSON.parse(line.slice(6));
                        //在这里处理消息,每次收到消息都会调用这个函数
                        
                    }
                });
            }
1
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2025/05/28, 16:40:57
mac使用docker部署nextcloud-aio并为本地域名添加https支持(未成功)
网站域名迁移的百度和谷歌SEO优化

← mac使用docker部署nextcloud-aio并为本地域名添加https支持(未成功) 网站域名迁移的百度和谷歌SEO优化→

最近更新
01
愚蠢错误收集
05-29
02
ubuntu安装g++显示已有但是输入g++又找不到命令
04-15
03
使用cloudflare-r2搭建webdav
04-08
更多文章>
Theme by Vdoing | Copyright © 2022-2025 PeaceSheep
冀ICP备2022004632号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式