-1

I struggle with connecting my client (or through Postman) to websocket server: if got 404 response when I try to connect and following prompts in console:

Access to XMLHttpRequest at 'http://localhost:8080/ws-endpoint/info?t=1670410538045' from origin 'http://localhost:5050' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET http://localhost:8080/ws-endpoint/info?t=1670410538045 net::ERR_FAILED 404

On the server side, while connecting if got:

2022-12-07T11:53:13.928+01:00  INFO 16292 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-07T11:53:13.928+01:00  INFO 16292 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-12-07T11:53:13.929+01:00  INFO 16292 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

My connection code in the client (run on the port 5050):

var socket = new SockJS('http://localhost:8080/ws-endpoint');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        updateNotificationDisplay();
        stompClient.subscribe('/topic/messages', function (message) {
            showMessage(JSON.parse(message.body).content);
        });
...

My config code on the server (port 8080):

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry) {
        registry.addEndpoint("/ws-endpoint").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/websocket");
    }
}

In setAllowedOrigins I tried with: *, http://localhost:5050, http://localhost:5050/**, https://localhost:5050 but still error remains.

BJagger
  • 181
  • 10
  • Looks like CORS may not be supported for `localhost`: https://stackoverflow.com/questions/10883211/why-does-my-http-localhost-cors-origin-not-work Consider playing around with your HOSTS file to get around this. – Henrik Aasted Sørensen Dec 07 '22 at 11:25

1 Answers1

0

I found the solution: the problem was in SockJs - I was using it instead of WebSocket - after switch, I have no longer problems with cors and connection was established

BJagger
  • 181
  • 10