3

While in other questions people claimt EventSource is fairly well documented I have found it to be more implied then explicit in some cases.

My understanding is that when you initialise an EventSource object in JS it opens a connection to your server using the specified URI.

Is this connection initiated using GET?

(Not sure if this constitutes a second question) Is it possible to use/force another HTTP Method (POST)?

CS Dude
  • 421
  • 4
  • 14
  • 2
    Have you [read the documentation](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface)? – Pointy Jan 21 '18 at 23:06
  • 2
    Actually it's pretty obscure from the docs; I *imagine* it's a GET, and there doesn't seem to be any way to make it anything else. – Pointy Jan 21 '18 at 23:09
  • I did read the docs, a few times now, most say something along the lines of "EventSource only works with GET" I interpreted this to mean the initial HTTP Request to obtain the page. – CS Dude Jan 21 '18 at 23:11
  • @Pointy after perusal of the linked documentation I found no mention of HTTP Method GET or POST, though I may be wrong... – CS Dude Jan 21 '18 at 23:14
  • 1
    The thing is, it's not 100% clear that the protocol is even HTTP in the first place. – Pointy Jan 21 '18 at 23:18
  • @pointy 100% agree at first I thought it was piggy backing off the initial HTTP Request, until I did my own investigation and saw the connection myself. – CS Dude Jan 21 '18 at 23:25
  • @OliverGiess _"I interpreted this to mean the initial HTTP Request to obtain the page"_ What do you mean by "initial request"? What are you trying to achieve? – guest271314 Jan 22 '18 at 00:28
  • No, you can use `EventSource` on pages loaded via POST or anything (or not HTTP at all, e.g. `file://`) just fine. – Bergi Jan 22 '18 at 01:23

1 Answers1

6

The request method when using the EventSource interface is a GET request. You can include a query string in the URL passed to the constructor and parse the query string at the server.

const stream = "data: event stream\n\n";
const blob = new Blob([stream], {type:"text/event-stream"});
const blobURL = URL.createObjectURL(blob);
const es = new EventSource(blobURL);
es.onmessage = e => {
   console.log(e.data);
}
es.onerror = e => {
   es.close();
}
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    @OliverGiess See also [Change source (url) of Server-Sent event](https://stackoverflow.com/q/42446195/), [How to read and echo file size of uploaded file being written at server in real time without blocking at both server and client?](https://stackoverflow.com/q/42475492/) – guest271314 Jan 22 '18 at 00:59