确保在使用框架代理时,保证关闭压缩中间件,vue配置devServer: { open: true, hot: true, proxy: {}, compress:false // 此处改为false },
react umi 需要 4版本才可以
UMI_DEV_SERVER_COMPRESS=none
默认 Umi 开发服务器自带 compress 压缩中间件,这会使开发时 SSE 数据的传输 无法流式获取 ,通过指定
UMI_DEV_SERVER_COMPRESS=none
来关闭 compress 压缩功能:
useEffect(() => {const evtSource = new EventSourcePolyfill(`http://localhost:3000/events`, {headers: {'content-type': 'text/event-stream;charset=utf-8',},});evtSource.onmessage = (event) => {console.log(event);// const data = JSON.parse(event.data);if (event.data === 'end') {evtSource.close();} else {setVm((prev) => [...prev, event.data]);}};}, []);
/** @Descripttion:* @version: 1.0.0* @Author: liuzicheng* @Date: 2024-11-27 11:14:02* @LastEditors: liuzicheng* @LastEditTime: 2024-12-04 10:56:50*/const express = require("express"); const app = express(); const port = 3000; const cors = require("cors");app.use(cors()); let strArr = ["1","2","3", ]; let setTask = null;app.get("/events", (req, res) => {res.setHeader("Content-Type", "text/event-stream;charset=utf-8");res.setHeader("Cache-Control", "no-cache");res.setHeader("Connection", "keep-alive");let num = 0;setTask = setInterval(() => {res.write(`data:${strArr[num]}\n\n`);num++;if (num > 2) {res.write(`data:end\n\n`);res.end();// res.closed()clearInterval(setTask);setTask = null;}}, 1000); });app.listen(port, () => {console.log(`${port}端口已启动`); });