错误
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.header (D:\node\javascript-demo\node_modules\express\lib\response.js:730:10)
at ServerResponse.send (D:\node\javascript-demo\node_modules\express\lib\response.js:170:12)
at Timeout.setInterval [as _onTimeout] (D:\node\javascript-demo\routes\eventsource\eventsource.js:8:8)
at ontimeout (timers.js:384:18)
at tryOnTimeout (timers.js:244:5)
at Timer.listOnTimeout (timers.js:214:5) Program node --debug ./bin/www exited with code 1
const express = require('express');
const router = express.Router();
router.get('/connect',function(req,resp,next){
resp.append('Content-Type','text/event-stream');
console.log(req.method);
setInterval((data)=>{
resp.send('hello!');
},1000,'hello');
});
router.get('/html',(req,resp,next)=>{
resp.render('./eventsource/msgsend_recevie.html');
});module.exports=router;
<!DOCTYPE html>
<html lang="en">
<head>
<title>EventSource消息发送</title>
<style type="text/css">
*{
margin:0 auto;
padding:0;
}
p{
width:440px;
height:450px;
border:2px solid;
margin-top:100px;
}
</style>
</head>
<body>
<p>
<textarea id="msg_recevie" rows="30" cols="60"></textarea>
</p>
<script>
//使用eventsource发送信息
var eventSource = new EventSource('/msg_send/connect');
eventSource.onmessage=function(e){
var tx=document.getElementsByTagName('textarea')[0];
tx.value=e.data;
};
</script>
</body>
</html>
我想大声告诉你2017-05-31 10:41:06
The problem has been solved. You need to add the "data:" prefix and "nn" suffix to the sent data, that is, "data"+msg+"nn"
The server code is modified as follows:
const express = require('express');
const router = express.Router();
router.get('/connect',function(req,resp,next){
resp.writeHead(200,{
"Content-Type":"text/event-stream",
"Cache-Control":"no-cache",
"Connection":"keep-alive"
});
setInterval(function(){
resp.write("data:"+Date.now()+"\n\n");
},1000);
});
router.get('/html',(req,resp,next)=>{
resp.render('./eventsource/msgsend_recevie.html');
});
module.exports=router;
给我你的怀抱2017-05-31 10:41:06
After the express response has been sent, the response is not allowed to perform a series of operations such as header. Setintval is a timer, and your logic method is not correct.
Your setintval has pushed the response out for the first time, so the subsequent response can no longer be operated. Since http is one-way but not two-way, the second time is an invalid operation
If you want the client to accept event push from the server, I recommend using socketio or ajax rotation to handle it.