PRVS
PRVS

Reputation: 1690

Using Server Sent Events in NodeJS not recieving data on client-side

I have one webpage with text input for one webpage and I want to obtain the information.

In the client I have this:

function login() {
    webpage = document.getElementById("webpage").value;
    alert(webpage);

    source = new EventSource(
        "http://localhost:8000/register?name="+webpage, 
        {'Access-Control-Allow-Origin' :'*'}
    );

    source.onmessage = function(event) {
        var a = event.data;
        alert(a);
    };
}

In the server I have this:

response.writeHead(200, {
    'Content-Type' : 'text/event-stream; charset=utf-8',
    'Cache-Control' : 'no-cache',
    'Connection' : 'keep-alive',
    'Access-Control-Allow-Origin': '*'
});

But, I'm trying to obtain the a and the alert(a) doesn't do nothing. Any idea what's the problem in this code? Or how to make it work? Suggestions in jQuery are also welcome.

Upvotes: 0

Views: 330

Answers (1)

laggingreflex
laggingreflex

Reputation: 34627

It seems you haven't actually sent any data from the server, just setting the headers doesn't do much.

You also need to actually send the events/data

res.write('event:data\n')

You're using Server Sent Events with NodeJS (something you may have been unaware of at the time of asking) so search around how to use it. Here's a good start.

Upvotes: 2

Related Questions