Server Sent Event script not working

Hi, I’m trying to implement a Server Sent Event on a website to listen to my stream.
I’m using the api.particle.io link. My code below doesn’t work, I’m just getting “Getting Server Updates”, but nothing else. Any suggests what I am doing wrong?

This is what the particle server is outputting at that link.

event: Valve 12345
data: {"data":"41.655807,-72.479919,1.100000,3.912500.0.000000,0.000000","ttl":60,"published_at":"2018-12-15T23:09:51.065Z","coreid":"21001c001947373334363431"}

My client side code.

<!DOCTYPE html>
<html>
<body>

<h3>Getting server updates</h3>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("https://api.particle.io/v1/devices/events?access_token=f74.......266a");
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

Hi @Bob_CT

I don't think the onmessage listener works for events that do not originate on your computer--it is for mouse/keyboard events. I always use the addEventListener for the event name or prefix. As a bonus you can add listeners for the opened and error events too.

There are bunch of tutorials but this one is the easiest:

2 Likes

You the Man!

Works.

Awesome!

1 Like

This method exposes the token. Is there a way to hide the token?

I could probably do a server to server SSE then store the results in a file, then use a php program to deliver the results to the client.

Hi @Bob_CT

Well PHP is good way to do a “last minute” substitute to put the token in a request as well. There are a few examples here in the forum if you search.

Another approach would be to use a Particle web hook, now called integrations. You can set up a Particle server to do the lifting for you and send you event to your server. What you are describing above mimics what Particle already offers so it is up to you if want to create your own server or use theirs.

1 Like

Thanks for your help.

What I’m really trying to do, is read the stream and write it to a file on the server.
Essentially creating a log file that a php program can read and write to a website.
I’m running into difficulty using javascript to write a disk file.

Can you suggest an alternative approach?