我正在编写一个代码来显示通知,但它遇到了错误。我的代码如下:
function notify() {
$response = new SymfonyComponentHttpFoundationStreamedResponse(function() {
while (true) {
$notification = Notification::where('user_ID', '=', Auth::user()->id)->get();
echo 'data: ' . json_encode($notification) . "nn";
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"。中止连接。
我该如何解决?我正在从教程服务器发送事件示例 laravel 编写此代码。
这对
我有用...
控制器
use SymfonyComponentHttpFoundationStreamedResponse;
public function notify(){
$response = new StreamedResponse(function() {
while(true) {
echo 'data: ' . 'Hello' . "nn";
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;
}