我正在编写代码来显示通知,但遇到错误。我的代码如下:
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;
}
并且在 View 中我添加了 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's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
我该如何解决?我正在从教程中编写这段代码 server-sent-events-example-laravel .
最佳答案
这对我有用...
Controller
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;
}
关于laravel-5 - Laravel 5 中的服务器发送事件抛出错误 "EventSource' s 响应具有 MIME 类型...”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29939197/