![](/img/trans.png)
[英]EventSource's response has a MIME type (“text/html”) that is not “text/event-stream”
[英]EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. header is set to text/event-stream
嗨,我在控制台中使用 sse 收到此错误
EventSource 的响应具有不是“text/event-stream”的 MIME 类型(“text/html”)。 中止连接。
js代码是:
if (typeof(EventSource) !== "undefined")
{
var source = new EventSource("../api/updateWellData.php?uid=<?php echo $node_id ?>");
source.onmessage = function(event) {
var response = JSON.parse(event.data);
document.getElementById("result").innerHTML = response.test;
// some code like the above line
};
}
else
{
// refresh the page every 30 secs
}
PHP代码是:
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/event-stream");
require_once("../resources/config.php");
if (isset($_GET['uid']))
{
$uid = $_GET['uid'];
while (1)
{
$query = Query("SELECT * FROM well_data_last WHERE well_detail_id = $uid");
$result = fetch_array($query);
echo json_encode($result);
ob_end_flush();
flush();
sleep(1);
}
}
这可能是 PHP 错误消息(所有这些都输出为原始 HTML),或者页面上的其他一些不符合text/event-stream
格式的text/event-stream
。
如果 PHP 文件的输出与text/event-stream
所需的格式不匹配,它将回退到使用text/html
。 Javascript 要求事件流使用text/event-stream
内容类型,因此 JS 控制台会显示错误,但这只是实际问题的症状 - 要解决问题,您需要修复 PHP。
在 OP 的情况下,问题在于他们的echo
语句。 输出到流的所有数据必须以data:
进行data:
,并以换行符\\n
结束。 流本身必须以另一个换行符结束,以指示没有更多data:
消息跟随。
要修复错误,OP 应该更改
echo json_encode($result);
到
echo "data: " . json_encode($result) . "\n\n";
OP 代码的另一个问题是在数据库查询中没有针对 SQL 注入的保护。 虽然这与手头的问题无关,但值得指出的是,应该使用准备好的语句。
我遇到了同样的问题,问题是 php 文件中的语法错误,它显示了一条错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.