SSE流数据请求处理

小程序支持

复制代码
     // 小程序支持
    const requestTask = uni.request({
      url: "http://192.168.1.66/chat/sse",
      timeout: 15000,
      responseType: "text",
      method: "post",
      enableChunked: true, //配置这里
      data: { question: "你好" },
      success: (response) => {
        console.log("成功", response);
      },
      fail: (error) => {
        console.log("失败", error);
      },
      complete: (res) => {
        let ret = JSON.stringify(res);
        console.log("完成", ret);
      },
    });
    requestTask.onHeadersReceived(function (res) {
      console.log("开始", res.header);
    });

    // 这里监听消息
    requestTask.onChunkReceived(function (res) {
      let decoder = new TextDecoder("utf-8");
      let str = decoder.decode(new Uint8Array(res.data));
      let falgData = JSON.parse(str.split("data: ")[1]);
      msg.value += falgData.data;
      console.log("接收数据", falgData.data);
      // setTimeout(() => {
      //   // 中断请求任务
      //   requestTask.abort();
      // }, 3000);
    });
复制代码

H5支持

复制代码
    // H5支持
    import { fetchEventSource } from "@microsoft/fetch-event-source";
    
    const ctrl = new AbortController(); //用于中断请求
    fetchEventSource("http://192.168.1.66/chat/sse", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        // "Content-Type": "text/event-stream",
      },
      body: JSON.stringify({
        question: "你好",
      }),
      // signal: ctrl.signal, // 用于中断请求
      onopen(response) {
        console.log("连接成功", response);
      },
      onmessage(msg) {
        console.log("接收", msg);
      },
      onclose() {
        console.log("连接关闭");
      },
      onerror(err) {
        console.log("连接错误", err);
      },
    });
复制代码

 

posted @   xuanPhoto  阅读(263)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示