I have a stream response like following:
I'm using Laravel as backend
public function stream() {
return response()->stream(function() {
while (true) {
if (connection_aborted()) {
Log::debug('aborted');
break;
}
echo "\nevent: process\n", 'data: {"time": ' . time() . '}', "\n\n";
Log::debug('echoed');
ob_flush();
flush();
sleep(3);
}
}, 200, [
'Cache-Control' => 'no-cache',
'Content-Type' => 'text/event-stream',
]);
}
frontend:
let stream = new EventSource(`http://example.test/api/stream`);
stream.addEventListener('process', event => {
console.log(event.data)
});
as the code show, it's expected to console.log(event.data) every 3 seconds.
Although I can get the echoed Logs (but not the aborted) in backend, but I can't get any output in the console of browser.
I've googled but nothing helps. How did this error occur and how can it be solved?
Thanks a lot for any replys!
Just add a response header
'X-Accel-Buffering' => 'no'
Setting this to “no” will allow unbuffered responses suitable for Comet and HTTP streaming applications. Setting this to “yes” will allow the response to be cached.
Refrences: