【问题标题】:CORS and Spring WebsocketCORS 和 Spring Websocket
【发布时间】:2018-04-07 18:52:05
【问题描述】:

我已经按照this tutorial 构建了一个提供websockets 连接的 Spring Boot 应用程序,但是除了 Spring Boot 本身提供的客户端之外,我无法从其他客户端连接到这些 websocket。

complete directory in the GitHub repository that accompanies the tutorial 包含最终的 Spring Boot 代码。我从这个存储库中获取了index.html 和app.js 文件,并创建了另一个在Node.js 服务器上运行的客户端。之后,我将连接字符串替换为指向localhost:8080(Spring Boot 正在运行的地方)。然后我运行 Node.js 服务器并尝试使用 websockets,但它不起作用。

通过将.setAllowedOrigins("*") 添加到StompEndpointRegistry 注册表很容易解决第一个问题。通过这个配置,我设法连接到 websocket,但现在我再也没有从 socket 收到消息了。

我想知道我错过了什么......有人知道问题出在哪里吗?

提取的index.html 和app.js(重命名为index.js)文件,以及用于测试目的的the Node.js server can be found here。要运行它,只需安装依赖项 (npm install),然后发出 npm start。服务器将回复http://localhost:3000/。

【问题讨论】:

    标签: spring spring-boot websocket cors stomp


    【解决方案1】:

    实际上这个问题/问题很愚蠢。问题是,当我将 HTML/JS 文件提取到外部应用程序时,我将代码中所有硬编码的三个点都更改为 http://localhost:8080/...:

    var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
    // ...
    stompClient.subscribe('http://localhost:8080/topic/greetings', cb);
    // ...
    stompClient.send("http://localhost:8080/app/hello", ...);
    

    我应该改变的唯一行是第一行。另外两个只是subscribe 和send 向已打开套接字上的主题发送消息的函数。因此,他们不需要 URL 作为前缀...

    var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
    // ...
    stompClient.subscribe('/topic/greetings', cb);
    // ...
    stompClient.send("/app/hello", ...);
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2021-06-14
      • 2021-11-09
      • 2020-05-02
      • 2020-06-15
      • 2023-03-08
      • 1970-01-01
      • 2020-03-15
      • 2019-07-16
      相关资源
      最近更新 更多