在前端开发中,特别是实时数据更新的场景下,EventSource
是一个非常实用的 API。它允许浏览器与服务器建立单向连接,服务器可以持续地发送数据给客户端,而无需客户端不断轮询。本文将详细介绍 EventSource
的使用方法、如何配置请求头及加参数,以及如何使用 EventSourcePolyfill
以兼容不支持该 API 的浏览器。
EventSource
是 HTML5 的一种浏览器 API,属于 Server-Sent Events(SSE) 机制,它使客户端可以订阅服务器的实时数据流。相较于 WebSocket,SSE 是单向的,只允许服务器向客户端发送数据。
EventSource
会自动尝试重新连接服务器。EventSource
的基本用法非常简单,下面我们通过一个例子来演示如何使用它从服务器接收实时消息。
首先,我们创建一个简单的 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()}\n\n`;
res.write(message);
}, 3000);
}).listen(3000, () => {
console.log('Server running on port 3000');
});
在上面的代码中,服务器通过 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);
};
运行后,客户端将每 3 秒接收到一次来自服务器的消息。
默认情况下,EventSource
无法直接配置请求头。不过我们可以通过以下两种方式为 EventSource
请求添加参数或请求头:
我们可以通过将参数附加到 URL 上来传递参数给服务器:
const eventSource = new EventSource('http://localhost:3000?token=12345&userId=alice');
服务器端可以通过 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);
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);
});
});
EventSource
在现代浏览器中大部分都支持,但如果你需要兼容一些不支持 EventSource
的旧版浏览器,可以使用 EventSourcePolyfill
来提供兼容性支持。
你可以通过 npm
安装 event-source-polyfill
:
npm install event-source-polyfill
或者使用 CDN 引入:
<script src="https://unpkg.com/event-source-polyfill/src/eventsource.min.js"></script>
引入 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);
};
使用了 EventSourcePolyfill
后,旧版浏览器也能支持 SSE 功能。
本文我们深入介绍了如何在前端使用 EventSource
接收服务器的实时推送消息,如何通过 URL 参数传递数据以及配置请求头,最后还介绍了如何使用 EventSourcePolyfill
使得 EventSource
能在旧版浏览器中正常工作。EventSource
是一种非常轻量级的实现实时数据更新的技术,适用于需要服务器单向推送消息的场景,特别是在实时数据展示和动态更新方面有广泛的应用。
因篇幅问题不能全部显示,请点此查看更多更全内容