javascriptphplaravelserver-sent-events

Server Sent Events (Laravel) not sending my content to client side


I am trying to send updates to client side using SSE, but when I trigger the event in the server side, the new data is not sent to client side.

My client side code:

<script>
  $(document).ready(function($) {

     var lastMsg = '';
     const source = new EventSource("/misc/getData");
     source.onmessage = function(event) {
        console.log(event);
        var data = JSON.parse(event.data);
        if (data !== lastMsg) {
           $('#result').empty();
           $('#result').append('Result: ' + data);
           lastMsg = data;
        }
     };
 });
 </script>

My server side code (Laravel class)

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class MiscController extends Controller {

   private $data;

   public function __construct() {
      $this->data = '';
   }


   public function sendContent(Request $request) {
      $content = $request['content'];
      if (!is_null($content)) {
         $this->data = "data:". $content ."\n\n";
      }
      $this->getData();
   }


   public function getData() {
      return response($this->data)->withHeaders(['Content-Type'=>'text/event-stream', 'Cache-Control'=>'no-cache']);
   }

}

No errors are shown, headers look ok in the browser console but I am not able to get the data when it is set by the server side.
The sendContent method is called on the server side by other classes or from the client side using AJAX, to set the content that needs to be reflected on the UI.

However, the onmessage function on the client side never gets it.

I also tried using a static method receiving the content as parameter, but to no avail.

What am I missing?


Solution

  • This is the answer to the CORS problem in Laravel.

    It is not the same version of Laravel I used before, but the issue is the same because I was not returning a Response Object appropriately. That is, with the right headers and with the content or payload wrapped in a Response object.

    Laravel 11 CORS issue