【问题标题】:Spring CORS policy error on WebSocket ApplicationWebSocket应用程序上的Spring CORS策略错误
【发布时间】:2021-11-02 13:29:55
【问题描述】:

在我的 Spring Boot Web 应用程序中,在 WebSocket 应用程序上出现 Spring CORS 策略错误,甚至配置了 WebMvcConfigure:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080","origin2","origin3");
            }
        };
    }

【问题讨论】:

  • 请检查How to Ask a Good QuestionHow to create a Minimal, Complete, and Verifiable example。你的问题必须清楚并且有足够的细节(到目前为止你做了什么研究?你尝试了什么?)以便社区可以提供帮助。谢谢!
  • 抱歉不清楚。在 Spring Boot Web 应用程序中,CORS 规则设置在 WebMvcConfigurer 对象中,但在特定情况下,我有一个 WebSocket 应用程序,其中 CORS 设置必须在 WebSocketMessageBrokerConfigurer 对象中,如下所示。

标签: spring websocket cors


【解决方案1】:

在这种情况下,我们需要在 WebSocketMessageBrokerConfigurer 上的 registerStompEndpoints 中配置 CORS,而不是 WebMvcConfigurer

解决办法是:

...
    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/websocketendpoint")
                .setAllowedOrigins(
                        "http://localhost:8080",
                        "origin2",
                        "origin3"
                )
                .withSockJS();
    }

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2022-11-12
    • 2019-12-09
    • 2020-06-03
    • 2021-08-14
    • 2021-11-14
    • 2021-02-13
    • 2021-10-13
    • 2021-11-09
    相关资源
    最近更新 更多