[英]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
Hi I get This error in my console using sse嗨,我在控制台中使用 sse 收到此错误
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". EventSource 的响应具有不是“text/event-stream”的 MIME 类型(“text/html”)。 Aborting the connection.
中止连接。
js code is : 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
}
The PHP Code is : 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);
}
}
This is my first time using sse I used the following documents : mozilla |这是我第一次使用 sse 我使用了以下文件: mozilla | w3schools
w3schools
This may be either a PHP error message (all of which are outputted as raw HTML), or some other text on the page which does not fit the text/event-stream
format .这可能是 PHP 错误消息(所有这些都输出为原始 HTML),或者页面上的其他一些不符合
text/event-stream
格式的text/event-stream
。
If the output of the PHP file does not match the format required by text/event-stream
, it will fall back to using text/html
.如果 PHP 文件的输出与
text/event-stream
所需的格式不匹配,它将回退到使用text/html
。 Javascript requires event streams use the text/event-stream
content type so the JS console will show an error, but this is just a symptom of the actual problem - to fix the issue you need to fix your PHP. Javascript 要求事件流使用
text/event-stream
内容类型,因此 JS 控制台会显示错误,但这只是实际问题的症状 - 要解决问题,您需要修复 PHP。
In OP's case, the issue is with their echo
statement.在 OP 的情况下,问题在于他们的
echo
语句。 All data outputted to the stream must be proceeded by data:
, and ended with a newline \\n
.输出到流的所有数据必须以
data:
进行data:
,并以换行符\\n
结束。 The stream itself must end with another newline to indicate that no more data:
messages follow.流本身必须以另一个换行符结束,以指示没有更多
data:
消息跟随。
To fix the error, OP should change要修复错误,OP 应该更改
echo json_encode($result);
to到
echo "data: " . json_encode($result) . "\n\n";
Another issue with OP's code is that there is no protection against SQL-injection in the database query. OP 代码的另一个问题是在数据库查询中没有针对 SQL 注入的保护。 While this is irrelevant to the issue at hand, it is worth pointing out that prepared statements should be used instead.
虽然这与手头的问题无关,但值得指出的是,应该使用准备好的语句。
我遇到了同样的问题,问题是 php 文件中的语法错误,它显示了一条错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.