uniapp 微信小程序,最简单的流式输出:Transfer-Encoding: chunked

在GPT项目中,流式输出是实现流畅对话体验的关键技术之一。今天,我们将探讨如何在uniapp开发的微信小程序中优雅地实现这一功能。虽然WebSocket是一种常见的解决方案,但在某些场景下,我们可能寻求更轻量级且易于集成的替代方案。本文将介绍一种基于Transfer-Encoding: chunked的HTTP请求方式,它不仅避免了WebSocket的复杂性,同时也绕过了微信小程序对XHR和EventSource的限制。

在微信小程序环境下,由于平台限制,XHR和EventSource并不总是可用,而WebSocket的部署和维护成本相对较高。因此,我们探索了一种更为直接的方法------利用HTTP协议中的Transfer-Encoding: chunked特性。

实现细节:Transfer-Encoding: chunked
Transfer-Encoding: chunked允许服务器以分块的方式发送数据,而无需事先知道整个响应的大小。这种方式特别适合于流式输出场景,因为它可以实时地将数据推送给客户端,而无需等待整个响应构建完成。对于uniapp小程序而言,这意味着可以即时更新UI,提供更流畅的用户体验。

后台不需要改动,继续采用流式输出的形式即可,以通义千问的demo为例,代码如下

复制代码
@RequestMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Result<CompletionsOutMsg>> completions(@RequestBody CompletionsInMsg inMsg) {
    ....
}

客户端处理:uniapp小程序

在uniapp小程序端,需要监听网络请求的onProgressUpdate事件或使用onChunkReceived回调来处理分块数据。下面是一个处理分块数据的示例代码:

复制代码
<template>
  <view class="page">
    <view class="box">
      <textarea class="uni-textarea" v-model="inputValue" placeholder="请输入内容"/>
    </view>
    <button class="mini-btn btn" type="primary" size="mini" @click="commit">提交</button>
    <view>
      {{ resultText }}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      resultText: '',
    };
  },
  methods: {
    commit() {
      var that = this;
      const requestTask = uni.request({
        url: 'YOUR_API_URL',
        method: 'POST',
        responseType: 'text',
        enableChunked: true,  //流式输出需要设置enableChunked为true
        data: {
          prompt: this.inputValue,
        },
        success: function (res) {
          console.log(JSON.stringify(res))
        },
        fail: function (err) {
        }
      });

      // 监听流式输出
      requestTask.onChunkReceived(function(res) {
        const uint8Array = new Uint8Array(res.data);
        let text = String.fromCharCode.apply(null, uint8Array);
        text = decodeURIComponent(escape(text));
        console.log(text);
        if (text) {
          let cleanedContent = text.replaceAll("data:", ',');
          let splitContent = "[" + cleanedContent.replace(/^,/, '') + "]";
          const dataArray = JSON.parse(splitContent);
          for (let i = 0; i < dataArray.length; i++) {
            that.resultText += dataArray[i].data.text;
          }
        }

      })


    },

  },


}
</script>

<style lang="scss">
.page {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
}

.box {
  padding: 20rpx;
}

.btn {
  text-align: center;
  margin-top: 20rpx;
}

.uni-textarea {
  border: solid 1px #a59d9d;
  padding: 20rpx;
  width: 100%;
}

</style>
相关推荐
JavaDog程序狗20 小时前
【指南】uni-app微信小程序多环境CI-CD完全指南
ci/cd·uni-app·jenkins
PedroQue9921 小时前
uni-router v2.1.0 升级:导航守卫全面支持返回值模式
前端·uni-app
weixin_BYSJ198721 小时前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
weixin_BYSJ198721 小时前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
show4331 天前
2026小程序工具生态技术趋势:轻量化免费替代桌面软件的路径解析
小程序
码云之上1 天前
小程序 iOS 多输入框焦点乱序脱坑记
ios·微信小程序·taro
ON.LIN2 天前
云边去水印小程序详细搭建教程(附源码)
小程序
2501_915909062 天前
iOS test 测试怎么做?功能、性能、兼容、稳定与安全五类测试指南
android·ios·小程序·https·uni-app·iphone·webview
deng1hao2 天前
2026小微企业企业邮箱选择指南:低成本高性价比方案
网络·科技·小程序
Ai-_Man2 天前
从AI公式到可编辑文档:MathType格式转换技术分析教程
人工智能·ai·小程序