Search code examples
springspring-bootcorsspring-websocketsockjs

Browser not connecting to Springboot Websocket (sockjs)


I have a SpringBoot server running on localhost:8080 and npm (serving a React app) on localhost:3000

Whenever I try to establish a websocket connection to spring, this shows up on the browser's console (Firefox Nightly):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/ws/info?t=1522629329791. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match 
‘http://localhost:8080/ws/info’).

I've created a WebSocketMessageBrokerConfigurer class and tried to setAllowedOrigins width both null and http://localhost:3000 (and 127.0.0.1 as well):

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws")
            .setAllowedOrigins("http://localhost:3000")
            .withSockJS();
}

REST requests are working fine, and I even made it to connect to the websocket in a simple node script, but within the browser I've had no luck. This is how I'm connecting in the browser (same as in script):

import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
...
let ws = new SockJS('http://localhost:8080/ws/');
let client = Stomp.over(ws);
client.connect({'some-header': 'some-data'}, (success) => {   
        //client.subscribe(...
}, (error) => {
    console.log(error)
})

Can someone help me? Thanks in advance.


Solution

  • I didn't manage to solve this with spring (on the server side) but I found a workaround. By using webpack (I used create-react-app, which uses webpack by default), one could simply proxy the requests to the "right" address:

      "proxy": "http://localhost:8080/"
    

    On package.json. Solves the problem when developing the application. But doesn't do anything for you on production. But since the webapp is served by tomcat (the compiled version (i.e., result of npm run build is placed on the server (src/main/resources/static), with a bit of configuration it's working fine.