Laravel 5中的服务器发送事件抛出错误“EventSource的响应具有MIME类型…”

3
我正在编写一段代码来显示通知,但是遇到了错误。我的代码如下:
 function notify() {
        $response = new Symfony\Component\HttpFoundation\StreamedResponse(function() {

        while (true) {
            $notification = Notification::where('user_ID', '=', Auth::user()->id)->get();

                echo 'data: ' . json_encode($notification) . "\n\n";
                ob_flush();
                flush();

            sleep(3);

        }
    });

    $response->headers->set('Content-Type', 'text/event-stream');
    return $response;
}

我已经添加了以下JavaScript代码:

<script type="text/javascript">
    var es = new EventSource("<?php echo action('NotificationController@notify'); ?>");
    es.addEventListener("message", function(e) {
        arr = JSON.parse(e.data);

           //apply some effect on change, like blinking the color of modified cell...
       // }
    }, false);

错误信息如下:

EventSource的响应MIME类型为"text/html"而不是"text/event-stream",因此连接已中止。

我该怎么解决?我正在按照教程server-sent-events-example-laravel编写代码。


我和你一样有同样的问题。当你将while循环在服务器端封装到一个函数中时,SSE无法正常工作。我仍在寻找原因并探究为什么封装循环在函数内时它不能正常工作,而本应该可以正常工作... - revobtz
1
请检查一下在过程模式下,注释函数是否能够通知并执行代码是否正常。 - revobtz
1个回答

1

这对我有用...

控制器

use Symfony\Component\HttpFoundation\StreamedResponse;

public function notify(){

    $response = new StreamedResponse(function() {
      while(true) {
          echo 'data: ' . 'Hello' . "\n\n";
          ob_flush();
          flush();
          sleep(3);
        }
    });

    $response->headers->set('Content-Type', 'text/event-stream');
    $response->headers->set('X-Accel-Buffering', 'no');
    $response->headers->set('Cach-Control', 'no-cache');
    return $response;
}

和中间件

public function handle($request, Closure $next)
{
    $response = $next($request);
    $response->headers->set('Content-Type', 'text/event-stream');
    $response->headers->set('Cache-Control', 'no-cache');
    $response->headers->set('X-Accel-Buffering', 'no');

    return $response;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接