Mercure 与 symfony 不与 vue 一起使用

问题描述

我在使用 vue 在 symfony 下配置 mercure 时遇到问题。我正在使用附加在 symfony cli 中的 mercure hub。在 .env 文件中,我将 mercure urls 更改为使用 http,因为它导致我的证书错误(由 symfony 包含)。

.env

MERCURE_URL=http://localhost:8000/.well-kNown/mercure
MERCURE_PUBLIC_URL=http://localhost:8000/.well-kNown/mercure
MERCURE_JWT_SECRET="!ChangeMe!"

当我通过在示例 http://localhost:8000 中打开 symfony 应用程序并在控制台中添加此脚本进行测试时:

const eventSource = new EventSource('http://localhost:8000/.well-kNown/mercure?topic=' + encodeURIComponent('http://example.com/books/1'));
eventSource.onmessage = event => {
    // Will be called every time an update is published by the server
    console.log(JSON.parse(event.data));
}

它正在工作,我可以在其他选项卡中发布一些更改。 但是,当我执行相同操作但在位于 http://localhost:8080 地址上的 vue 应用程序中时,它会在控制台错误显示

Access to resource at 'http://localhost:8000/.well-kNown/mercure?topic=http://example.com/books/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我还有两个问题:

  1. 为什么当我在 env 中粘贴 jwt 令牌时出现 401 错误,但上面的却没有?
  2. 为什么我不能通过 https 使用 symfony 服务?我收到“TransportException: fopen(): Unable to locate certificate CN”的错误

解决方法

是因为 CORS,因为 VueJS 运行的域和安装 Mercure 的域不同。
我将 Mercure 与 Docker compose 结合使用,但如果您从 CLI 启动它,请尝试添加 --cors-allowed-origins='http://localhost:8000 http://localhost:8080'

其他问题 1:我认为,您应该在 .env 和 mercure 配置中使用相同的秘密

  • .envMERCURE_JWT_SECRET="Secret123"
  • 当您开始使用 mercure 时:--jwt-key='Secret123'