[英]Server sent events showing blank in chrome devtools for simple express SSE
Here is the simple code sample to send SSE using express program (which is working fine).这是使用 express 程序发送 SSE 的简单代码示例(工作正常)。 Only trouble is the devtools eventStream section is blank.
唯一的问题是 devtools eventStream 部分是空白的。
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/countdown', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
"Access-Control-Allow-Origin": "*"
})
countdown(res, 10)
})
function countdown(res, count) {
res.write(JSON.stringify({ count: count}))
if (count)
setTimeout(() => countdown(res, count-1), 1000)
else
res.end()
}
app.listen(3000, () => console.log('SSE app listening on port 3000!'))
You must format the event like that :您必须像这样格式化事件:
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/countdown', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
countdown(res, 1, 10);
});
function countdown(res, id, count) {
res.write(`id: ${id}\n`);
res.write('event: count\n');
res.write(`data: ${JSON.stringify({ count: count })}\n\n`);
if (count) setTimeout(() => countdown(res, id + 1, count - 1), 1000);
else res.end();
}
app.listen(3000, () => console.log('SSE app listening on port 3000!'));
And in your front page useEventSource
:在您的首页使用
EventSource
:
<script>
var source = new EventSource('http://localhost:3000/countdown');
source.onmessage = function(event) {
console.log(event);
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.