前端fetch 实现流式接口

遇到这样一个需求,通过ai动态生成大纲文本,前端在接收到后端的文本内容时,接收的文本是“动态”的,视角表现层面上逐字生成渲染的,效果如下,那么如何实现这种效果?这里就要用到流式接口,也就是流式传输。

什么是流式传输

  先说说传统传输吧,我们日常接触的大多数是传统传输方式,就也是整段传输,前后端将数据一次性传送给对方;相比于传统传输方式,流式传输则采用分段的方式将要传输的数据分层n段,后端一次性传一段给前端,直到传输完成为止,当然在传输的过程中,前端也可以提前中断传输,后端收到中断传输的消息后,也不再继续往前端传输剩下没传完的数据段。 当然,前端流式传输需要在后端支持分块传输的情况下才能实现。

前端实现流式传输的几种主流方式

查阅了资料,目前前端实现流式传输主要有以下几种方式:fetch、SSE、websocket,详情移步另一位博主,没错我查阅的资料就是他的文章,链接chatGPT流式输出前端实现fetch、SSE、websocket_fetch sse-CSDN博客

我用的是fetch,fetch 本身不直接支持流式输出,但你可以使用fetch ai 中的 ReadableStream实现流式数据处理。

什么是fetch?

简单来说fetch 是一种 HTTP 数据请求的方式, XMLHttpRequest(以下简称 XHR)的一种替代方案。与基于回调的API的XMLHttpRequest不同,fetch是基于Promise的,可以链式分块化地处理数据,更重要的是Fetch API能够处理流式响应。

更多关于fetch 的文档可以参考以下文档,我们重点讲fetch 处理流式响应

fetch 官方文档: 官方文档 

 js ES6 fetch 方法_js fetch-CSDN博客

fetch实现流式输出的实现原理_fetch nodejs 客户端 流式输出-CSDN博客

fetch处理流式响应

要实现 fetch 的流式输出,关键在于如何正确地处理返回的 ReadableStream 对象。ReadableStream 是 HTML 标准的一部分,它代表了一个可以从内部读取数据的源头。在 Fetch API 中,Response 对象的 body 属性就是一个 ReadableStream 实例。


   
   
  1. return fetch(input, { ...init, headers })
  2. . then( (res) => {
  3. console. log( 'res.body', res. body);
  4. if (res. ok) return Promise. resolve(res);
  5. })

实现步骤:

  1.创建一个阅读器并将流锁定到它。


   
   
  1. //创建一个阅读器并将流锁定到它。当流被锁定时,在这个阅读器发布之前,无法获得其他阅读器
  2. const reader = res_. body. getReader();
  3. return reader. read(). then( ({ value, done }) => {
  4. console. log( 'value', value);
  5. });

          

 可以看到阅读器一次只接收一次响应数据,且接收到的数据为utf-8编码数据,这时我们需要让阅读器重复获取数据(发布这个阅读器),直到数据获取完或者手动中止为止,并且还要对 utf-8编码数据进行转码

2. 发布阅读器我们 可以使用递归函数去重复发布阅读器


   
   
  1. const reader = res_. body. getReader();
  2. return reader. read(). then( function push( { value, done }) {
  3. console. log( 'done, value', done, value);
  4. return reader. read(). then(push);
  5. });

 3. 转码的话我们需要使用 文本解码器(TextDecoder)进行转码 ,详情可以看我另一篇文章浅识TextDecoder-CSDN博客


   
   
  1. const reader = res_. body. getReader();
  2. const utf8Decoder = new TextDecoder( 'utf-8');
  3. return reader. read(). then( function push( { value, done }) {
  4. let _value = value ? utf8Decoder. decode(value, { stream: true }) : '';
  5. console. log( '转码后的数据', _value);
  6. return reader. read(). then(push);
  7. });

4.中止fetch
  要中止不完整的fetch()操作,请使用AbortControllerAbortSignal接口。

   定义

  const controllerRef = useRef(null);

   
   

   
   
  1. controllerRef. current = new AbortController();
  2. const signal = controllerRef. current. signal;
  3. fetch(input, { headers, signal })

  使用

 <button onClick={() => controllerRef.current.abort()}>停止生成 </button>

   
   

5.完整代码


   
   
  1. //存储中断器
  2. const controllerRef = useRef( null);
  3. const getStreamData = ( ) => {
  4. const input = 'xxxxxx';
  5. //fetch 其它配置项
  6. const token = utils. getToken();
  7. const headers = {
  8. ...(token ? { Authorization: 'Bearer ' + token } : null),
  9. };
  10. controllerRef. current = new AbortController();
  11. const signal = controllerRef. current. signal;
  12. //存储拿到的数据
  13. let outline = '';
  14. fetch(input, { headers, signal })
  15. . then( (res) => {
  16. //res.ok 表示成功状态
  17. if (res. ok) return Promise. resolve(res);
  18. })
  19. . then( (res_) => {
  20. //创建一个阅读器并将流锁定到它。当流被锁定时,在这个阅读器发布之前,无法获得其他阅读器
  21. const reader = res_. body. getReader();
  22. const utf8Decoder = new TextDecoder( 'utf-8');
  23. //定义一个对象存储每次拿到的数据
  24. return reader. read(). then( function push( { value, done }) {
  25. if (done) {
  26. //表示数据流结束
  27. return outline;
  28. } else {
  29. let _value = value ? utf8Decoder. decode(value, { stream: true }) : '';
  30. let _data = _value?. split( '\n\n') || [];
  31. for ( const it of _data) {
  32. let _it = it. replace( /^(data: \[DONE\])|^(data:)/, '');
  33. if (_it) {
  34. let res: { code; data; msg } = JSON. parse(_it);
  35. if (res?. code == 0) {
  36. outline = outline + res?. data?. text;
  37. console. log( '接收到的数据为:', outline);
  38. } else {
  39. return Promise. reject(res);
  40. }
  41. }
  42. }
  43. }
  44. return reader. read(). then(push);
  45. });
  46. });
  47. };

​​​​​​​

​​​​​​​

 
  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值