Angular 使用 sockJs 和 Stomp 实现 websocket 出现 CORS 错误

问题描述 投票:0回答:1

我使用Stomp和SockJS来实现WebSocket,我们的后端是使用Spring Boot构建的。 这是我的客户代码:

baseApi 是这样的:

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

这是我在网络选项卡中得到的内容:

当我单击此错误时,我收到 200 状态代码。这很奇怪:

了解更多详情:

当我使用 Chrome CORS 安全模式打开项目时,一切正常

另外,当我单独打开“https://api.test.com”时,它可以在没有 CORS 的情况下工作

此外,我的后端开发人员为此地址设置了allowed-origin

我还放了我们的后端配置代码:

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()
    }
}
angular spring-boot websocket spring-websocket
1个回答
0
投票

就我而言

访问控制允许来源

设置了多个值,我们将这部分代码放在后端,现在它可以工作了。

春天:

cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_UNIQUE
© www.soinside.com 2019 - 2024. All rights reserved.