客户端如下所示:
var es = new EventSource("http://localhost:8080");
es.addEventListener("message", function(e) {
alert("e.data") //Alerts "" every couple seconds
})
es.addEventListener("error", function(e) {
alert("error") //Also fires every couple of seconds
})
var post_request = new XMLHttpRequest();
post_request.open("POST", "http://localhost:8080");
post_request.setRequestHeader("Content-Type", "text/plain");
post_request.addEventListener("readystatechange", function() {
if (post_request.readyState == 4 && post_request.status == 200) {
alert(post_request.responseText); //This works
}
})
post_request.send("This is a test")
处理 POST 请求的服务器端 Node.js 如下所示:
function process_request(request, response) {
var request_body = []
request.on("data", function(chunk) {
request_body.push(chunk)
})
request.on("end", function() {
request_body = Buffer.concat(request_body).toString()+"\n"
response.writeHead(200, {"Access-Control-Allow-Origin": "*",
"Content-Type": "text/event-stream",
"Connection": "keep-alive"
});
response.end("data: " + request_body + "\n");
})
}
response.end()
如果我从客户端发送 POST 请求数据,它会按预期返回给我,但es
每隔几秒就会触发一个错误,此外每隔几秒就会触发一个message
事件。但是,当message
事件被触发时,它会发出警报""
,我不确定为什么?谁能帮我弄清楚这种行为?
编辑:刚刚检查了es.readyState
和message
事件error
。readyState
在0
上error
,所以看起来可能是断开连接的结果。为什么会发生这种反复断开连接?为什么重复连接和断开会导致重复message
事件?