CORS 和 Spring Websocket

Bru*_*ebs 4 spring stomp websocket cors spring-boot

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

complete教程附带的 GitHub 存储库中目录包含最终的 Spring Boot 代码。我从这个存储库中获取了index.htmlapp.js文件,并创建了另一个在 Node.js 服务器上运行的客户端。之后,我将连接字符串替换为指向localhost:8080(运行 Spring Boot 的位置)。然后我运行 Node.js 服务器并尝试使用 websockets,但它不起作用。

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

我不知道我错过了什么......有谁知道是什么问题?

提取index.htmlapp.js(重命名为index.js)文件以及Node.js 服务器可以在此处找到以进行测试。要运行它,只需安装依赖项 ( npm install),然后发出npm start. 服务器将响应http://localhost:3000/

Bru*_*ebs 5

实际上这个问题/问题很愚蠢。问题是,当我将 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", ...);
Run Code Online (Sandbox Code Playgroud)

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

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