【问题标题】:Symfony 5 / Mercure > Private update. Fetch CORSSymfony 5 / Mercure > 私人更新。获取 CORS
【发布时间】:2023-03-22 21:14:02
【问题描述】:

我尝试将 Mercure 集成到 symfony 5 项目中。还有两个麻烦。

  1. 我尝试将更新发送到私人,但它不起作用,但如果尝试发送到非私人一切正常。

运行mercure的命令:

./bin/mercure --jwt-key='homesphere_secret_token' --addr='localhost:3000' --allow-anonymous --cors-allowed-origins='*'

.env 文件

MERCURE_PUBLISH_URL=http://localhost:3000/.well-known/mercure
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.P0f5r123SLTru4DiE4X9q0EIoKahds-nI8jpo8uKKQQ
MERCURE_SECRET_KEY=homesphere_secret_token

提供 url 和 jwt 令牌的后端

    $user = $this->getUser();

    $hubUrl = $this->getParameter('mercure.default_hub');
    $link = new Link('mercure', $hubUrl);

    $token = JWT::encode([
        'mercure' => [
            'publish' => [sprintf("/chat/%s", $user->getId())],
        ],
    ], $this->getParameter('mercure_secret_key'));

更新代码

    $message = $serializer
        ->serialize(['message' => $message], 'json');
    $update = new Update(
        sprintf("/chat/%s", $user->getId()),
        $message,
        true // if false then work
    );
    $publisher($update);

前端部分

const hub = new URL('http://localhost:3000/.well-known/mercure');
hub.searchParams.append('topic', '/chat/1');
const eventSource = new EventSourcePolyfill(hub.href, {
  'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiXC9jaGF0XC8xIl19fQ.yg3DodPjaPzWVIOhKMo30xXzS3L4oPckbL9pcA4tMck'
});
eventSource.onmessage = event => {
  console.log(JSON.parse(event.data));
}
  1. 当前端通过更新接收到消息时,下一个请求开始出现 CORS 问题 image

有人可以帮我解决这些吗?

【问题讨论】:

    标签: symfony mercure


    【解决方案1】:

    试试 --cors-allowed-origins='http://localhost:8000'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 2021-05-09
      • 1970-01-01
      • 2021-11-15
      • 2021-09-03
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多