我有一个symfony 5.0/API-platform后端项目和一个react/redux前端项目,我想向连接的客户端发送更新(POST、PUT、DELETE)。为此,我在windows 10 PC上尝试在本地实现这一点,我安装了mercure,通过我从文档中了解到的内容,我配置了实体和环境变量如下:
/**
- @ApiResource(mercure=true) \*/ class Affectation { ..... }MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.IbDnbK-5K3WB2LX9n5pYn6bLF2YispnFSUQkWqOvzHc MERCURE_PUBLISH_URL=http://localhost:3001/.well-known/mercure
MERCURE_SUBSCRIBE_URL=
然后我跑了
mercure.exe --jwt-key="my-jwt" --addr=":3001" --allow-anonymous --cors-allowed-origins="*" 一切看起来都很好,因为我收到了日志信息。就在我尝试通过客户端订阅(选项卡控制台日志)以合并更新之后,我在浏览器选项卡控制台中运行了这个脚本
const eventSource = new EventSource('http://localhost:3001/.well-known/mercure?topic=' + encodeURIComponent('http://localhost:8000/affectations/53'));
eventSource.onmessage = event => {
// Will be called every time an update is published by the server
console.log(event);
}到目前为止,我尝试使用postman或edge浏览器发出POST/ PUT /DELETE请求,最酷的是,我看到在mercure控制台中发布了一些更新,这是一个日志示例,位于postman发送的PUT请求之后:
time="2020-08-27T12:22:07+01:00" level=info msg="Mercure started" addr=":3001" protocol=http
time="2020-08-27T12:22:09+01:00" level=info msg="New subscriber" last_event_id= remote_addr="127.0.0.1:60537" subscriber_id="urn:uuid:9ae4a3d9-9ccb-41cc-8168-21a73326d773" subscriber_topics="[http://localhost:8000/affectations/53]"
time="2020-08-27T12:22:36+01:00" level=info msg="Subscriber disconnected" last_event_id= remote_addr="127.0.0.1:60537" subscriber_id="urn:uuid:9ae4a3d9-9ccb-41cc-8168-21a73326d773" subscriber_topics="[http://localhost:8000/affectations/53]"
127.0.0.1 - - [27/Aug/2020:12:22:09 +0100] "GET /.well-known/mercure?topic=http%3A%2F%2Flocalhost%3A8000%2Faffectations%2F53 HTTP/1.1" 200 4 "http://localhost:3000/adminpanel" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
time="2020-08-27T12:22:53+01:00" level=info msg="New subscriber" last_event_id= remote_addr="[::1]:60588" subscriber_id="urn:uuid:7f9265cd-cea2-4674-9dd0-2a49193d4b81" subscriber_topics="[http://localhost:8000/affectations/53]"在浏览器中的“网络”选项卡中,我可以注意到从后端服务器接收到的更新(服务器在从订阅的客户端触发事件之后发出事件调用),但它们缺少新更新的数据。我不知道我错过了什么,任何帮助都将不胜感激。
发布于 2020-08-28 13:16:22
在使用调试器之后,根据我的项目结构,我似乎没有从mercure获得任何更新,因此我更改了脚本,以查看来自中心的更新。
* BACK_END_API是一个环境变量,(this.props.hubURL)来自我的redux商店。
componentDidUpdate() {
if (this.props.hubURL) {
const url = new URL(this.props.hubURL + `?topic=${BACK_END_API}/affectations/{id}`);
const eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
}
}
}发布于 2020-08-27 23:28:23
你不需要静态地传递装腔作势的id,所以代替这个
new EventSource('http://localhost:3001/.well-known/mercure?topic=' + encodeURIComponent('http://localhost:8000/affectations/53'));做这个
new EventSource('http://localhost:3001/.well-known/mercure?topic=http://localhost:8000/affectations/{id}));https://stackoverflow.com/questions/63615075
复制相似问题