Spring Websocket CORS issue

Discussão em 'Angular' iniciado por Testing, Março 27, 2025.

  1. Testing

    Testing Guest

    I have a web application served by an Angular frontend and Spring Boot backend. They are deployed with a multi-stage Docker build on the same server. I had an issue of the websocket on Angular not connecting to the Spring websocket until I allowed CORS on the Spring websocket.

    Does anyone know why this is the case? I thought that since they are on the same server, they should work even without CORS.

    Here's my code:

    Angular:

    onConnect(): Promise<any> {
    return new Promise(resolve => {
    console.log("Connecting...")
    this.ws = new WebSocket(`wss://${window.location.host}/websocket`)
    this.ws.onopen = this.onWebSocketOpen.bind(this)
    this.ws.onmessage = this.onWebSocketMessage.bind(this)
    this.ws.onclose = this.onWebSocketclose.bind(this)
    this.ws.onerror = (error) => console.error(error)
    resolve(this.ws)
    })
    }


    Spring Boot:

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {

    @Value("${webapp.host.url}")
    private String hostUrl;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(new WebSocketHandler(), "/websocket");
    .setAllowedOrigins(hostUrl);
    }
    }


    When CORS was not set, the Angular websocket connection failed with an close stats of 1006, reason ''. However, Postman is able to connect.

    Continue reading...

Compartilhe esta Página