NodeJS Express 中建立html5的server-sent event服務端

sourcenode發表於2019-02-16

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() + `

`); //後面必須帶有`

`,否則不會觸發
    });

參考:
http://javascript.ruanyifeng….

相關文章