-1

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.

New contributor
Testing is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.