Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to use server sent events for the first time. I am creating a very simple test:

// sse-test.php
header("Content-type: text/event-stream");
header("Cache-Control: no-store");
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
// inside index.html
const source = new EventSource("sse_test.php");
// check headers  
fetch('/sse-test.php')
.then(res => {
  for (let value of res.headers.values()) {
    console.log(value)

The EventSource constructor throws a EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection error. I am logging the response headers and they seem to be correct, they include a text/event-stream; header.

What am I missing?

Could it be not using the leading forward-slash on your EventSource() call? Which OS/browser is it? Take a look at the developer tools - that is a simpler way to troubleshoot if the correct headings are being sent than using fetch(). – Darren Cook Dec 15, 2022 at 12:02 I added the slash to the EventSource() call but the same thing happens. The fetch test was unecessary indeed, I see from the developer tools that I am getting the text/html content type. I am using Windows 10 with the github.com/cretueusebiu/valet-windows environment. This is using the nginx server, and maybe this needs some configuration for SSE to run properly. – Alex P Dec 17, 2022 at 8:32

You do not send an AJAX request to the Event Source server - you connect as you do above using new EventSource but then bind event handlers to the returned event-stream

A fully working basic example might help.

if( isset( $_GET['sse'], $_GET['evt'] ) && $_GET['sse']=='go' ){ # this script will run infinitely whilst client is connected so no timeout set_time_limit( 0 ); # ensure no stray characters in event stream other than those created in the sse function below ob_end_clean(); # repeat the infinite loop after a delay $sleep=1; # the name of the event.. this is sent in the connection url $evt=$_GET['evt']; #utility to send a correctly formatted message function sse( $evtname='sse', $data=null, $retry=1000 ){ if( !is_null( $data ) ){ echo "event:".$evtname."\r\n"; echo "retry:".$retry."\r\n"; echo "data:" . json_encode( $data, JSON_FORCE_OBJECT | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS ); echo "\r\n\r\n"; # ensure that this header is set before starting the infinite loop. header('Content-Type: text/event-stream'); while( true ){ Do whatever needs to be done - query db, query remote api, perform calculations etc prepare payload to send $payload=array( 'data' => rand( 0, 100 ), 'date' => date( 'Y-m-d H:i:s' ) #send the packet sse( $evt, $payload ); # flush buffers if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush(); @flush(); # take it easy for a while before doing it all again. sleep( $sleep ); <!DOCTYPE html> <meta charset="UTF-8" /> <title>Welcome!</title> </head> <div id="result"></div> <script> const evt='SOME_EVENT_NAME'; // single page - connect with querystring parameters let sse = new EventSource( '?sse=go&evt='+evt ); // bind the event listener and process response from server. sse.addEventListener(evt,e=>{ console.log(e.data); document.getElementById("result").innerHTML=e.data; </script> </body> </html> I think he was just using fetch() to troubleshoot, i.e. to confirm that the correct headers were being sent? BTW, interesting example to combine HTML and the SSE PHP in one file; I'd never tried that. – Darren Cook Dec 15, 2022 at 12:05 One can inspect the text-stream using the console as one would for AJAX requests - no need for the separate ajax request. The only thing I notice about the @OPs code is the disparity between the url used for the EventSource and the Fetch request. I guess it is possible that one of these is not found, thus the non text/event-stream headers – Professor Abronsius Dec 15, 2022 at 12:34

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.