我正在设置一个Web界面,我希望服务器动态发送数据以更新图形。我找到了SSE(服务器发送事件),但我不知道如何使用它。我尝试重试,但每次遇到此错误时:“ EventSource的响应具有不是“ text / event-stream”的MIME类型(“ text / html”)。中止连接。”这怎么工作?
我已经尝试查找是否定义了其他内容类型,但是没有定义。 我知道.on(event,function)不能捕获事件。
这是我的一些代码: 从“路径”导入路径; 从“快递”进口快递 从'./config.js'导入配置 从“ ./frontend/frontend.module”导入前端 从“ ./backend/backend.module”导入后端
const EventEmitter = require('events');
var app = new express();
const Stream = new EventEmitter();
//Try to configure SSE
app.get('/stream', function(request, response){
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
Stream.on("push", function(event, data) {
console.log("RESPONSE 0");
response.write("event: " + String(event) + "\n" + "data: " + JSON.stringify(data) + "\n\n");
response.send();
response.end();
console.log("RESPONSE 1") ;
});
});
setInterval(function(){
Stream.emit("push", "test", { msg: "admit one" });
console.log("\nEMIT");
}, 5000)
//Stop Trying here
app.use(function(req, res, next){
console.log(req.url);
next();
});
// Import sub-apps
app.use("/api", Backend.App)
app.use("/", Frontend.App)
// Enable CORS (for debugging -- better way?)
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
})
// Point static path to dist
app.use('/assets', express.static(path.join(__dirname, 'app/assets')));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
const port = process.env.PORT || config.port;
app.listen(port, function () {
console.log('Server listening on port ' + port);
});
我让客户在听:
var es = new EventSource("http://127.0.0.1:8081/") ;
es.onmessage = function(event){
console.log("ONMESSAGE "+event.data);
}
我阅读了很多有关此错误的文章,但找不到解决方案,请有人可以帮助我吗?