一、原生EventSource

(一)定义:

MDN详解:Web API 接口参考>EventSource

(二)使用方式:

  const eventSource = new EventSource('/api/test');
  // 正常的EventSource,我们只关心以下三个事件
  /*
  * open:订阅成功(和后端连接成功)
  */
  eventSource.addEventListener("open", function(e) {
    console.log('open successfully')
  })
  /*
  * message:后端返回信息,格式可以和后端协商
  */
  eventSource.addEventListener("message", function(e) {
    console.log(e.data)
  })
  /*
  * error:错误(可能是断开,可能是后端返回的信息)
  */
  eventSource.addEventListener("error", function(err) {
    console.log(err)
    // 类似的返回信息验证,这里是实例
    err && err.status === 401 && console.log('not authorized')
  })
  
  // 需要关闭了
  eventSource.close()

Tip:我们值得注意的语法:new EventSource(url, configuration)
看一下MDN:

// 1、参数
(1) url:一个USVString ,它代表远程资源的位置
(2) configuration 可选:为配置新连接提供选项。
	可选项是:withCredentials,默认为 false,指示 CORS 是否应包含凭据( credentials )// 2、返回值
一个新建的 EventSource 对象,如果指定了configuration, 则按其配置;否则,配置为合适的基本默认值。

发现要是更自定义的配置,比如加header什么的就不行了,所以我找了找合适的封装后的库,还真找到了:
github地址:EventSource polyfill

二、EventSource polyfil

(一)使用方式

import { EventSourcePolyfill } from 'event-source-polyfill';
const eventSource = new EventSourcePolyfill('/api/test', {
  headers: {
    'X-Custom-Header': 'value'
  }
});
/*
  * open:订阅成功(和后端连接成功)
  */
  eventSource.addEventListener("open", function(e) {
    console.log('open successfully')
  })
  /*
  * message:后端返回信息,格式可以和后端协商
  */
  eventSource.addEventListener("message", function(e) {
    console.log(e.data)
  })
  /*
  * error:错误(可能是断开,可能是后端返回的信息)
  */
  eventSource.addEventListener("error", function(err) {
    console.log(err)
    // 类似的返回信息验证,这里是实例
    err && err.status === 401 && console.log('not authorized')
  })
  
  // 需要关闭了
  eventSource.close()

基本使用方法如此,此文只是工作中遇到使用,具体定义MDN写的很清楚了,如有疑问也可留言与我交流,最后的最后,希望能帮到大家解决业务问题!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐