クライアント側では、次のようになります。なぜこのイベントソースはメッセージとエラーを繰り返しトリガしていますか?
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のようになります。私は、クライアント側からPOSTリクエストデータを送信する場合、それは私に返される
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()
と予想されますが、es
は、数秒ごとにmessage
イベントに加えて、2秒ごとにエラーをトリガーしています。しかし、message
イベントがトリガされたときには""
が警告されます。理由はわかりません。誰も私がこの行動を把握するのを助けることができますか?
編集:message
とerror
イベントでes.readyState
をチェックしただけです。 readyState
はerror
の0
なので、切断された可能性があります。この繰り返しの切断はなぜ起こるのですか?なぜ繰り返し接続と切断が繰り返されるのでしょうか?message
イベントが繰り返されますか?
「これはテストです」は 'text/event-stream'コンテンツでは有効ではありません。あなたは実際に有効な応答の本文を書こうとしましたか? – mscdex
@mscdex私はそれを有効な 'text/event-stream'コンテンツにするために編集しました。ここで何が起きるかは、 'es'が' message'イベントと 'error'イベントの両方を数秒ごとに引き起こすということです。しかし、 'message'イベントの' alert(e.data) 'は空文字列を警告しますか? – digglemister