angularspring-bootwebsocketspring-websocket

Angular implementing websocket using sockJs and Stomp getting CORS Error


I used Stomp and SockJS for implementing WebSocket, and our backend is built with Spring Boot. this is my client code: code

and baseApi is something like this:

 baseApi: 'https://api.test.com'

this is what I get in the network tab: cors

and when I click on this error I receive a 200 status code. that is weird:

status

for more detail:

When I open my project with Chrome CORS safe mode, everything works fine

also when I open "https://api.test.com" separately, it works without CORS

additionally, my backend developer set allowed-origin for this address

I also put our backend configuration codes:

application.yml:

spring:
  config:
    name: staging
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allow-credentials: false
            allowed-origins:
              - 'https://api.test.com'
            max-age: 3600
            allowed-headers: '*'
            allowed-methods:
              - POST
              - GET
              - PUT
              - OPTIONS
              - DELETE

WebSocketConfig.kt:

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig(
    @Value("\${app.white-labels-list}")
    private val whiteLabelList: Array<String>
) : WebSocketMessageBrokerConfigurer {
    override fun configureMessageBroker(config: MessageBrokerRegistry) {
        config.enableSimpleBroker("/topic")
        config.setApplicationDestinationPrefixes("/app")
    }

    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        registry.addEndpoint("/websocket-endpoint")
            .setAllowedOrigins(*whiteLabelList)
            .withSockJS()
    }
}

Solution

  • in this case

    Access-Control-Allow-Origin

    It seems set twice, put this part of the code to the backend side.

    spring:

    cloud:
        gateway:
          default-filters:
            - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_UNIQUE