首页 > 解决方案 > 美居码头无法正确配置 CORS 问题

问题描述

我尝试了几个小时来使用 docker 配置我的 Mercure,但未能解决 corss 问题:

已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

我有这个 docker-compose 文件

提炼

  mercure:
    image : dunglas/mercure
    volumes:
      - ./mercure/caddy:/etc/caddy
    ports:
      - "8081:80"
      - "443:443"
    environment:
      - SERVER_NAME=localhost
      - MERCURE_SUBSCRIBER_JWT_KEY=changeIt
      - MERCURE_PUBLISHER_JWT_KEY=changeIt
      - MERCURE_CORS_ALLOWED_ORIGINS=*
      - ALLOW_ANONYMOUS=1

而这个 Caddyfile :

# The address of your server
localhost

:80
route {
    mercure {
        # Publisher JWT key
        publisher_jwt changeIt
        # Subscriber JWT key
        subscriber_jwt changeIt
        cors_origins http://localhost:3000
    }

    respond "Not Found" 404
}

我在客户端的请求在 React 中

http.get('/api/mercure').then( response => {
            this.setCookie( response.data.token);
            const url = new URL('http://localhost:8081/.well-known/mercure');
            url.searchParams.append('topic', 'http://agora.org/votes/{id}');
            const eventSource = new EventSource(url, {withCredentials: true});
            eventSource.onmessage = (data) => {
                console.log(data);
            }
        },error => {
            console.log( error);
        })

有人可以帮我解决这个问题吗?提前谢谢

标签: reactjsdockermercure

解决方案


我已经成功地使用了docker-compose没有 CORS 问题的 Mercure。你可以在这里找到实现。

正如我到达这里,其他人也可能到达这里,也可能帮助那个人。


推荐阅读