CORS and Spring Websocket

Viewed 5021

I have followed this tutorial to build a Spring Boot application that serves websockets connections but I can't connect to these websockets from other clients than the one served by Spring Boot itself.

The complete directory in the GitHub repository that accompanies the tutorial contains the final Spring Boot code. I took the index.html and the app.js files from this repository and created another client that runs on a Node.js server. After that, I replaced the connection strings to point to localhost:8080 (where Spring Boot is running). Then I ran the Node.js server and tried to use the websockets, but it does not work.

The first problem was easily solved by adding .setAllowedOrigins("*") to the StompEndpointRegistry registry. With this configuration, I managed to connect to the websocket, but now I never get a message back from the socket.

I wonder what am I missing... Does any one know what is the problem?

The extracted index.html and app.js (renamed to index.js) files, and the Node.js server can be found here for testing purposes. To run it, simply install the dependencies (npm install) and then issue npm start. The server will respond on http://localhost:3000/.

1 Answers

Actually the question/problem was quite stupid. The problem was that when I extracted the HTML/JS files to an external application, I changed all hardcoded three points in the code to 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", ...);

The only line that I should have changed was the first one. The other two are just functions to subscribe and send message to topics on an already-open socket. Therefore, they don't need the URL as the prefix...

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