Client side looks like this:
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")
Server side Node.js handling POST request looks like this:
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");
})
}
If I send POST request data from the client side, it gets returned to me with response.end()
as expected, but es
is triggering an error every couple of seconds, in addition to a message
event every couple of seconds. When themessage
event is triggered, however, it alerts ""
, and I'm not sure why? Can anyone help me figure out this behavior?
EDIT: Just checked the es.readyState
on the message
and error
events. readyState
is 0
on the error
, so it seems like it might be a result of getting disconnected. Why would this repeated disconnecting happen? And why would repeated connecting and disconnecting cause repeated message
events?