1、搭建NodeJS项目
1)确认本地安装node,执行命令:
node -v
出现版本号即为安装成功
2)创建一个文件夹专门存放nodejs项目
3)进入项目文件夹
cd hello
4)安装Express脚手架
npm install -g express
npm install -g express-generator
5) 新建项目
express -t ejs 项目名称
6)按照提示进入项目目录,运行npm安装
//进入项目目录
cd newsproject
//输入命令安装
npm install
7)运行项目
//项目目录下运行命令
node app.js
8)浏览器访问:http://127.0.0.1:3000/即可见nodejs站点页面,页面输出:Express
2、使用独立 Express 服务器模拟 SSE
1)创建 Express 服务器文件
新建 server.js(和app.js同级,放在项目根目录即可):
const express = require('express');
const cors = require('cors');
const app = express();
const fs = require('fs');
const path = require('path');
// 允许跨域
app.use(cors());
// 模拟 SSE 接口
app.get('/sse-stream', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// 模拟流式数据推送
const messages = ['Hello ', ',', '', 'this ', 'is ', 'a ', 'EventStream ', 'demo!'];
let index = 0;
const timer = setInterval(() => {
if (index < messages.length) {
const data = {
"choices":[
{
"delta":{
"content": `${messages[index++]}`,
"type":"text",
"timestamp": Date.now()
},
},
],
"model":"",
"message_id":2,
};
res.write(`data: ${JSON.stringify(data)}\n\n`); // SSE 格式要求
} else {
clearInterval(timer);
res.end();
}
}, 500);
});
});
// 启动服务器
app.listen(3001, () => {
console.log('SSE Server running on http://localhost:3001');
});
2)安装依赖并启动服务器
npm install express cors
node server.js
运行页面展示如下:
3)在 Vue 组件中连接外部 SSE 接口
<template>
<div class="ceshi-wrap">
<h3 style="color:red;">来自本地文件的 SSE 流数据:</h3>
-----
<ul>
<li v-for="item in messages" :key="item.id">
<span v-for="item1 in item" :key="item1.delta.timestamp" v-html="item1.delta.content" style="white-space: pre;">
</span>
</li>
</ul>
+++++
</div>
</template>
mounted() {
const eventSource = new EventSource('http://localhost:3001/sse-stream');
// 监听消息事件
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
this.messages.push(data.choices);
};
// 监听错误并关闭连接
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
eventSource.close();
};
// 组件销毁时关闭连接(避免内存泄漏)
this.$once('hook:beforeDestroy', () => {
eventSource.close();
});
}
4)验证:启动vue项目
npm run serve
说明:
1)SSE 数据格式
每个事件必须以 data: 开头,以 \n\n 结尾:
data: {"choices":[{"delta":{"content":"Hello ","type":"text","timestamp":1741691346932}}],"model":"","message_id":2}\n\n
2)自动重连
EventSource 默认会在断开后尝试重连,可通过 eventSource.close() 手动关闭。
3)在使用v-html最后展示时,会把空格去掉,想要让空格正常显示的话,可以添加css:
white-space: pre;