首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

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

  • 25-03-05 15:41
  • 2268
  • 10660
blog.csdn.net

前言

在前端开发中,特别是实时数据更新的场景下,EventSource 是一个非常实用的 API。它允许浏览器与服务器建立单向连接,服务器可以持续地发送数据给客户端,而无需客户端不断轮询。本文将详细介绍 EventSource 的使用方法、如何配置请求头及加参数,以及如何使用 EventSourcePolyfill 以兼容不支持该 API 的浏览器。

目录

  1. 什么是 EventSource
  2. EventSource 基本使用
  3. EventSource 配置请求头及加参数
  4. EventSourcePolyfill 的使用
  5. 总结

1. 什么是 EventSource

EventSource 是 HTML5 的一种浏览器 API,属于 Server-Sent Events(SSE) 机制,它使客户端可以订阅服务器的实时数据流。相较于 WebSocket,SSE 是单向的,只允许服务器向客户端发送数据。

适用场景
  • 实时更新,例如股票价格、新闻推送、赛事比分等。
  • 服务器频繁向客户端推送数据的场景,替代轮询机制。
特点
  • 单向通信:服务器向客户端发送消息,客户端不能向服务器发送消息。
  • 自动重连:当连接断开时,EventSource 会自动尝试重新连接服务器。
  • 轻量级:比 WebSocket 更轻量,基于 HTTP 协议,适合需要稳定且轻量的消息传输。

2. EventSource 基本使用

EventSource 的基本用法非常简单,下面我们通过一个例子来演示如何使用它从服务器接收实时消息。

服务器端(Node.js)代码示例

首先,我们创建一个简单的 Node.js 服务来定时发送一些消息给客户端:

// server.js
const http = require('http');

http.createServer((req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Access-Control-Allow-Origin': '*',
    });

    setInterval(() => {
        const message = `data: Server time: ${new Date().toLocaleTimeString()}

`;
        res.write(message);
    }, 3000);

}).listen(3000, () => {
    console.log('Server running on port 3000');
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

在上面的代码中,服务器通过 text/event-stream 向客户端发送持续的数据流。

客户端代码示例

在客户端,我们使用 EventSource 来接收来自服务器的数据:

// client.js
const eventSource = new EventSource('http://localhost:3000');

eventSource.onmessage = function(event) {
    console.log('Received message:', event.data);
};

eventSource.onerror = function(event) {
    console.error('EventSource error:', event);
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

运行后,客户端将每 3 秒接收到一次来自服务器的消息。


3. EventSource 配置请求头及加参数

默认情况下,EventSource 无法直接配置请求头。不过我们可以通过以下两种方式为 EventSource 请求添加参数或请求头:

1. URL 参数

我们可以通过将参数附加到 URL 上来传递参数给服务器:

const eventSource = new EventSource('http://localhost:3000?token=12345&userId=alice');
  • 1

服务器端可以通过 URL 查询参数来解析这些值:

// server.js
const url = require('url');

http.createServer((req, res) => {
    const query = url.parse(req.url, true).query;
    const token = query.token;
    const userId = query.userId;

    console.log(`Received token: ${token}, userId: ${userId}`);

    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
    });

    // 省略其他代码...
}).listen(3000);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
2. 使用 XMLHttpRequest 或 fetch 创建 EventSource

由于 EventSource 不允许直接配置请求头,因此可以通过 XMLHttpRequest 或 fetch 创建长连接,然后使用其 response 作为 EventSource 的输入。此方法可以绕过 EventSource 直接配置请求头的限制。

fetch('http://localhost:3000', {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer your-token-here',
        'Custom-Header': 'value'
    }
}).then(response => {
    const reader = response.body.getReader();
    reader.read().then(function processText({ done, value }) {
        if (done) {
            return;
        }
        // 将读取到的内容转换为字符串
        console.log(new TextDecoder().decode(value));
        return reader.read().then(processText);
    });
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

4. EventSourcePolyfill 的使用

EventSource 在现代浏览器中大部分都支持,但如果你需要兼容一些不支持 EventSource 的旧版浏览器,可以使用 EventSourcePolyfill 来提供兼容性支持。

安装 EventSourcePolyfill

你可以通过 npm 安装 event-source-polyfill:

npm install event-source-polyfill
  • 1

或者使用 CDN 引入:


  • 1
使用 EventSourcePolyfill

引入 EventSourcePolyfill 后,它会自动替换浏览器中的原生 EventSource,其用法与原生的 API 一致。你可以像使用 EventSource 一样使用它:

const EventSourcePolyfill = require('event-source-polyfill');

const eventSource = new EventSourcePolyfill('http://localhost:3000');

eventSource.onmessage = function(event) {
    console.log('Received message from polyfill:', event.data);
};

eventSource.onerror = function(event) {
    console.error('EventSourcePolyfill error:', event);
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

使用了 EventSourcePolyfill 后,旧版浏览器也能支持 SSE 功能。


5. 总结

本文我们深入介绍了如何在前端使用 EventSource 接收服务器的实时推送消息,如何通过 URL 参数传递数据以及配置请求头,最后还介绍了如何使用 EventSourcePolyfill 使得 EventSource 能在旧版浏览器中正常工作。EventSource 是一种非常轻量级的实现实时数据更新的技术,适用于需要服务器单向推送消息的场景,特别是在实时数据展示和动态更新方面有广泛的应用。

注:本文转载自blog.csdn.net的m0_74823983的文章"https://blog.csdn.net/m0_74823983/article/details/144403248"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

104
前端
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top