我有一个快速测试 Symfony 应用程序正在运行以尝试集成 Mercure 协议。
我有一个测试 Mercure 集线器,运行以下内容:
JWT_KEY='aVerySecretKey' ADDR='localhost:3000' ALLOW_ANONYMOUS=1 CORS_ALLOWED_ORIGINS=* ./mercure
我有一个将数据提交到以下端点的表单:
/**
* @Route("/resources", name="resourcesPost", methods={"POST"})
*/
public function resourcesPost(Publisher $publisher, Request $request){
$user = $this->getUser();
$update = new Update(
'http://example.com/books/1',
json_encode([
'from' => $user->getFullName(),
'sent at' => (new DateTime())->format('H:i:s'),
'message' => $request->request->get('message'),
])
);
$publisher($update);
return $this->redirectToRoute('resources');
}
一旦我点击表单,我会在调试器中得到以下信息:
127.0.0.1 - - [19/Jun/2019:13:27:40 -0400] "GET /hub?topic=http%3A%2F%2Fexample.com%2Fbooks%2F1&topic=http%3A%2F%2Fexample.com%2Fbooks%2F2&topic=http%3A%2F%2Fexample.com%2Freviews%2F%7Bid%7D HTTP/1.1" 200 31 "http://localhost:8888/resources" "Mozilla/5.0 (Windows N
T 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"
time="2019-06-19T13:32:50-04:00" level=info msg="Subscriber disconnected" remote_addr="127.0.0.1:65391"
time="2019-06-19T13:32:53-04:00" level=info msg="Update published" event_id=cd3acff1-7e9b-4e28-b6ba-e79aeb4c1791 remote_addr="127.0.0.1:49546"
127.0.0.1 - - [19/Jun/2019:13:32:53 -0400] "POST /hub HTTP/1.0" 200 36 "" ""
time="2019-06-19T13:32:53-04:00" level=info msg="Event sent" event_id=cd3acff1-7e9b-4e28-b6ba-e79aeb4c1791 remote_addr="127.0.0.1:65384"
但是,正在侦听的第二个浏览器上的 javascript 不会将响应放入控制台日志中:
const u = new URL('http://localhost:3000/hub');
u.searchParams.append('topic', 'http://example.com/books/1');
// Subscribe to updates of several Book resources
u.searchParams.append('topic', 'http://example.com/books/2');
// All Review resources will match this pattern
u.searchParams.append('topic', 'http://example.com/reviews/{id}');
const es = new EventSource(u);
let lastEventId = null;
es.onmessage = e => {
let data = JSON.parse(e.data);
lastEventId = e.lastEventId;
console.log(data);
}
如果我回到终端并运行ctrl+c
(以终止 Mercure 服务器),则数据将被推送到 javascript 中。我的问题是如何让它自动将数据推送到 javascript 而无需终止 Mercure 服务器(在 localhost:3000 上运行)然后重新启动它?