1、客戶端程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Server-Sent</title>
</head>
<body>
<div id="result"></div>
<!--js-->
<script>
var source = new EventSource(`/source.interface`); //資料介面
source.onmessage = function(event){
document.getElementById(`result`).innerHTML += event.data + `<br>`;
}
</script>
</body>
</html>
2、Nodejs後臺程式碼
var express = require(`express`);
var router = express.Router();
router.get(`source.interface`, function(req, res, next){
res.setHeader(`Content-Type`, `text/event-stream`);
res.setHeader(`Cache-Control`, `no-cache`);
res.send(`data:` + new Date() + `
`); //後面必須帶有`
`,否則不會觸發
});