前端调用sse接口,限制最大访问次数,SSE手动终止请求

因为sse请求要定义请求头,请求方式,和传参,所以使用了fetchEventSource插件

1.安装依赖

npm install @microsoft/fetch-event-source

2.引入

import { fetchEventSource } from "@microsoft/fetch-event-source";

3.使用

const getThinkText = async (
  apiUrl: string,
  partNum: any,
  params: any,
  callBack: Function,
  step: String
) => {
  let retryCount = 0; //记录重新连接次数
  const MAX_RETRIES = 5; //定义最大请求次数

  const ctrlAbout = new AbortController();  //定义连接实例
  fetchEventSource(sseUrl + apiUrl, {
    signal: ctrlAbout.signal, //用于手动终止请求
    method: "POST", //请求方式
    //请求头
    headers: {
      Authorization: "Bearer " + localStorage.getItem("token"),
      "Content-Type": "application/json",
      "Cache-Control": "no-cache",
      Connection: "keep-alive",
      "Access-Control-Allow-Origin": "*",
    },
    body: JSON.stringify(params), //传参
    openWhenHidden: true,//  保持连接,即使页面隐藏
    async onmessage(event: any) {
    
      if (event.data) {
          //处理逻辑
      }
    },
    async onclose(ee: any) {
      // 关闭流
    
      console.log("连接已关闭");
    },
    onerror(error: any) {
      // 这里检查是否是因为请求被中止
      retryCount++;
      if (retryCount >= MAX_RETRIES) {
       
        console.error("超过最大重试次数,终止连接");
        throw new Error("终止连接"); // 会导致fetchEventSource 停止重连
        //返回流报错
      } else {
       //重新请求的逻辑处理
      }
    },
  });

  return ctrlAbout; //返回连接,用于手动终止请求
};

4.手动终止请求使用方法

//调用请求方法
const getPart = async () => {

  const res = await getThinkText(
    "XXXXXX", //请求地址
    1,
    params, //请求参数
    getResultFun,
    "XXXX" // 参数
  );
  ctrlAbout1.value = res; //拿到连接
};

//暂停请求的方法
const pausePart = () => {
    if (ctrlAbout1.value) {
        ctrlAbout1.value.abort(); // 确保仅在请求中进行暂停
    }
};

你可能感兴趣的:(前端,SSE,vue.js,javascript,长链接)