现在Ai越来越火,可以很久你的问题实时回答输出内容,下面简单用 node 的 express 中间件简单搭建一个服务器,在使用 H5 的 EventSource 来实现实时输出,下面是实现代码:
<template>
<div>
<button @click="startEventSource">开始接收事件</button>
<button @click="stopEventSource">停止接收事件</button>
<div v-for="event in events" :key="event.id">
{{ event.data }}
</div>
</div>
</template>
<script>
export default {
name: 'EventSourceExample',
data() {
return {
events: [],
eventSource: null
};
},
methods: {
startEventSource() {
if (!this.eventSource) {
this.eventSource = new EventSource('http://localhost:3000/api/stream');
this.eventSource.onmessage = this.handleMessage;
this.eventSource.onerror = this.handleError;
}
},
stopEventSource() {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
}
},
handleMessage(event) {
// 处理接收到的消息
console.log('收到消息:', event.data);
this.events.push({ id: this.events.length, data: event.data });
},
handleError(event) {
// 处理错误
console.error('EventSource 错误:', event);
this.stopEventSource();
}
},
beforeDestroy() {
// 组件销毁前停止 EventSource
this.stopEventSource();
}
};
</script>
const express = require('express');
const app = express();
app.get('/api/stream', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Access-Control-Allow-Origin', '*');
// 模拟实时事件
setInterval(() => {
res.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
}, 1000);
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
589

被折叠的 条评论
为什么被折叠?



