收藏
回答

requestTask.onChunkReceived为什么真机和开发者工具触发的次数不一样?

 这个时真机返回的数据,并且数据被切割了

这个时模拟器触发的,每次都是完整的


 // 2. 发起分块流式请求

    const requestTask = wx.request({

      url: `https://lawapi.chkjnotary.com/api/MiniProgram/Chat/Contract/Inspect/SimpleTest`,

      method: "POST",

      header: {

        Accept: "text/event-stream",

        "Auth-token": '65d0e62d283542bfb4eb74ca705201847',

        'Content-Type': 'text/plain; charset=utf-8;'

      },

      data,

      dataType: "json",

      responseType: "text",

      enableChunked: true,

      success(res) {

        console.log("连接成功")

      },

      fail(err) {

        console.error("请求失败:", err)

      },

    })

    // 3. 监听数据流(核心逻辑)

    requestTask.onChunkReceived(async (res) => {

      console.log('res', res.data);

    })


回答关注问题邀请回答
收藏

2 个回答

  • 如日
    如日
    2025-08-27
    可以考虑一下,真机连接的后端的相关sse接口有没有禁用nginx缓存,需要手动禁用缓存。可以参考:
    # 设置 Nginx 不对 SSE 响应进行缓冲,直接透传给客户端
    proxy_buffering off;
    
    
    # 设置代理读取服务器响应的超时时间
    proxy_read_timeout 24h;
    
    
    # 设置客户端连接的超时时间
    proxy_connect_timeout 1h;
    
    
    # 设置 HTTP 版本,SSE 需要 HTTP/1.1
    proxy_http_version 1.1;
    
    
    # 保持连接活性,不发送连接关闭的信号
    proxy_set_header Connection '';
    
    
    # 配置代理传递的头部,确保 Host 头部正确传递
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    
    
    # 设置代理的响应头部,保持传输编码为 chunked
    proxy_set_header X-Accel-Buffering no;
    
    
    # 设置流式响应头
    proxy_set_header Accept "text/event-stream";
    proxy_set_header Cache-Control "no-cache";
    
    
    # 禁用压缩
    proxy_set_header Accept-Encoding "";
    
    
    # 设置跨域资源共享 (CORS)
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Origin,Authorization,Accept,X-Requested-With,Content-Type' always;
    
    
    
    2025-08-27
    有用
    回复
  • sun
    sun
    发表于小程序端
    2025-04-19

    流式数据传输就是这样的,流式传输是不保证数据的顺序的。例如你传输的是1,2,3,可能收到的是3,1,2。需要开发者自行在前端做逻辑自行处理数据顺序。

    2025-04-19
    有用
    回复 2
    • x
      x
      2025-04-21
      你说的这个我知道的,但是现在是用一个数据,在真机和模拟器,onChunkReceived触发的频率不一样,它返回的字节流的大小很大区别
      2025-04-21
      回复
    • sun
      sun
      发表于小程序端
      2025-04-21回复x

      这也是正常的。流式传输服务器发送一次数据,客户端可能会分多次收到。

      2025-04-21
      回复
登录 后发表内容