前端怎么用 EventSource? EventSource怎么配置请求头及加参数? EventSourcePolyfill使用方法

EventSource

EventSource 接口是 web 内容与服务器发送事件通信的接口。

一个 EventSource 实例会对 HTTP 服务器开启一个持久化的连接,以 text/event-stream 格式发送事件,此连接会一直保持开启直到通过调用 EventSource.close() 关闭。

EventSource 服务器发送事件是单向的。数据消息只能从服务端发送到客户端。

如果想了解更多请查看 EventSource 文档

EventSource使用方式

这里其实和webSocket 使用方式其实很像

这里需要注意 我在网上查了说参数可以配置headers(请求头) 实际使用的时候我这边传入请求头是没有生效(可能是我操作有误吧)

首先先安装EventSource
 npm install eventsource

示例代码

//创建一个新的 EventSource 对象的同时,你可以指定一个接受事件的 URI
// 如果需要加参数的话是在url 后面拼接参数 sysm/user/1
  const eventSource = new EventSource('url')
  //与事件源的连接刚打开时触发
  eventSource.onopen = function (e) {
        console.log(e, "连接刚打开时触发");
      };
    /*
       * message:后端返回信息,格式可以和后端协商
       */

      eventSource.onmessage = function (e) {
        console.log(e,'后端返回信息,格式可以和后端协商');
      };
       /*
       * error:错误(可能是断开,可能是后端返回的信息)
       */
      eventSource.onerror = function (e) {
        console.log(e, "连接无法打开时触发");

        eventSource.close(); // 关闭连接
        setTimeout(() => {
        //关闭连接后重新调用 

        }, 5000);
      };
      // 关闭连接
    // eventSource.close();   

EventSourcePolyfill 是EventSource封装的一个方法,EventSourcePolyfill 可以配置请求头

EventSourcePolyfill可以配置请求头 目前我EventSource配置请求头不生效所以才用 EventSourcePolyfill

首先先安装 EventSourcePolyfill

 npm install event-source-polyfill

引用 EventSourcePolyfill

import { EventSourcePolyfill } from "event-source-polyfill";

示例代码

// 如果需要加参数的话是在url 后面拼接参数 sysm/user/1
 const eventSource = new EventSourcePolyfill(
        `${process.env.VUE_APP_BASE_API}/sysm/user/1`,
        {
          heartbeatTimeout:3*60*1000,//这是自定义配置请求超时时间  默认是4500ms(印象中是)
          headers: {
            Authorization: "Bearer " + 'token',
          },
        }
      );
      /*
       * open:订阅成功(和后端连接成功)
       */
      eventSource.onopen = function (e) {
        console.log(e, "连接刚打开时触发");
      };
      /*
       * message:后端返回信息,格式可以和后端协商
       */

      eventSource.onmessage = function (e) {
        console.log(e,'后端返回信息,格式可以和后端协商');
        const data = JSON.parse(e.data) || {};//这里后端返回的是字符串所以目前我这边有转换

      };
      /*
       * error:错误(可能是断开,可能是后端返回的信息)
       */
      eventSource.onerror = function (e) {
        console.log(e, "连接无法打开时触发");

        eventSource.close(); // 关闭连接

        setTimeout(() => {

        }, 5000);
      };

      // 需要关闭了
      // eventSource.close();
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编写 EventSource前端使用方法如下: 1. 创建 EventSource 对象: ```javascript var eventSource = new EventSource('/your-event-stream'); ``` 2. 添加事件监听器来处理接收到的事件: ```javascript eventSource.addEventListener('eventName', function(event) { // 在这里处理接收到的事件数据 var eventData = JSON.parse(event.data); // ... }); ``` 3. 可选:添加错误处理的事件监听器: ```javascript eventSource.addEventListener('error', function(event) { // 在这里处理错误 console.error('EventSource error:', event); }); ``` 4. 可选:关闭 EventSource 连接: ```javascript eventSource.close(); ``` 5. 在服务器端,你需要设置一个路由来处理客户端的 EventSource 连接请求,并发送事件数据给客户端。这个路由需要返回以下的响应头信息: ```javascript Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive ``` 6. 在服务器端,你需要按照以下格式发送事件数据给客户端: ```javascript response.write('event: eventName\n'); response.write('data: ' + JSON.stringify(eventData) + '\n\n'); response.flush(); // 确保数据被发送到客户端 ``` 其中,`eventName` 是你定义的事件名称,`eventData` 是你要发送的事件数据。 请注意,EventSource 使用的是长轮询技术,在客户端与服务器之间维持一个持久连接。服务器会发送新的事件数据给客户端,而客户端则使用事件监听器来处理接收到的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值