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() + '\n\n'); //后面必须带有'\n\n',否则不会触发
    });

参考:
http://javascript.ruanyifeng....


sourcenode
307 声望29 粉丝

以少聚多,持之以恒!