以下是一个使用 Axios 和 HTTP SSE 的代码示例:

import axios from 'axios';

// 使用 Axios 创建 HTTP SSE 请求
const eventSource = new EventSource('/sse');

// 监听 SSE 事件
eventSource.addEventListener('message', (event) => {
  console.log(event.data);
});

// 监听 SSE 错误
eventSource.addEventListener('error', (error) => {
  console.error('SSE Error:', error);
});

// 发送 HTTP SSE 请求
axios.get('/sse', {
  headers: {
    'Cache-Control': 'no-cache',
    'Content-Type': 'text/event-stream',
  },
  responseType: 'stream',
})
  .then(response => {
    // 处理 SSE 响应数据流
    response.data.on('data', (chunk) => {
      const lines = chunk.toString().split('
');
      lines.forEach((line) => {
        if (line.trim() !== '') {
          eventSource.dispatchEvent(new MessageEvent('message', { data: line }));
        }
      });
    });
  })
  .catch(error => {
    console.error('Axios Error:', error);
  });

在这个示例中,我们使用 Axios 发送一个 GET 请求到 /sse 路径,并使用 responseType: 'stream' 指定响应数据的流式传输。我们还设置了一些 SSE 所需的请求头参数,如 Cache-ControlContent-Type

在请求成功时,我们将返回的数据流分割成单独的行,并将每行分发到 SSE 事件处理程序中。这使得我们可以在 SSE 事件监听器中处理数据,并在需要时执行其他操作。

当发生错误时,我们会在控制台输出错误信息。

Axios HTTP SSE 代码示例:实时数据流处理

原文地址: https://www.cveoy.top/t/topic/nhM0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录