服务器发送的事件在chrome devtools中显示空白,用于简单表达SSE

问题描述 投票:1回答:1

这是使用Express程序发送SSE的简单代码示例(运行正常)。唯一的麻烦是devtools eventStream部分为空白。Empty event stream

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!'))
node.js google-chrome-devtools server-sent-events
1个回答
1
投票

您必须这样格式化事件:

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!'));

并且在首页中使用EventSource

EventSource

<script> var source = new EventSource('http://localhost:3000/countdown'); source.onmessage = function(event) { console.log(event); }; </script>

© www.soinside.com 2019 - 2024. All rights reserved.