html5 - EventSource報(bào)錯(cuò)
問(wèn)題描述
錯(cuò)誤
Error: Can’t set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)at ServerResponse.header (D:nodejavascript-demonode_modulesexpresslibresponse.js:730:10)at ServerResponse.send (D:nodejavascript-demonode_modulesexpresslibresponse.js:170:12)at Timeout.setInterval [as _onTimeout] (D:nodejavascript-demorouteseventsourceeventsource.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消息發(fā)送</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 rows='30' cols='60'></textarea> </p> <script>//使用eventsource發(fā)送信息var eventSource = new EventSource(’/msg_send/connect’);eventSource.onmessage=function(e){ var tx=document.getElementsByTagName(’textarea’)[0]; tx.value=e.data;}; </script></body> </html>
問(wèn)題解答
回答1:問(wèn)題已解決,需要給發(fā)送的數(shù)據(jù)加上'data:'前綴,'nn'后綴,即'data'+msg+'nn'服務(wù)端代碼修改如下:
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()+'nn'); },1000);});router.get(’/html’,(req,resp,next)=>{ resp.render(’./eventsource/msgsend_recevie.html’);});module.exports=router;回答2:?jiǎn)栴}
在express的response已經(jīng)send后,response不允許再進(jìn)行header等一系列的操作,setintval是一個(gè)定時(shí)器,你的邏輯方式?jīng)]有正確。你的setintval第一次已經(jīng)把響應(yīng)推送出去了,那么后面這個(gè)響應(yīng)已經(jīng)不能繼續(xù)操作了,由于http是單向非雙向的,所以第二次是無(wú)效的操作
解決方案如果你希望客戶(hù)端能夠接受服務(wù)端得事件推送的話(huà),我推薦使用socketio,或者使用ajax輪訓(xùn)去處理。
相關(guān)文章:
1. windows誤人子弟啊2. php傳對(duì)應(yīng)的id值為什么傳不了啊有木有大神會(huì)的看我下方截圖3. python - linux 下用wsgifunc 運(yùn)行web.py該如何修改代碼4. python - oslo_config5. 關(guān)于mysql聯(lián)合查詢(xún)一對(duì)多的顯示結(jié)果問(wèn)題6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 冒昧問(wèn)一下,我這php代碼哪里出錯(cuò)了???8. mysql優(yōu)化 - MySQL如何為配置表建立索引?9. MySQL主鍵沖突時(shí)的更新操作和替換操作在功能上有什么差別(如圖)10. 數(shù)據(jù)庫(kù) - Mysql的存儲(chǔ)過(guò)程真的是個(gè)坑!求助下面的存儲(chǔ)過(guò)程哪里錯(cuò)啦,實(shí)在是找不到哪里的問(wèn)題了。
