【问题标题】:CORS error with Spring boot, javascript and web socketSpring boot、javascript 和 web socket 的 CORS 错误
【发布时间】:2021-12-11 19:40:16
【问题描述】:

我正在做一个小测试项目,其中一个简单的 html 页面(使用 javascript)作为前端,一个 Spring Boot 应用程序用于我的 apis 作为后端。我使用带有 stomp 和 sockJS 的 websocket 来保持前后之间的连接。我的问题如下:当我测试与 Postman 的连接时我没有问题,但是当我从我的 javascript 调用 api 时出现以下错误:

我尝试了我在互联网上找到的所有解决方案,但现在我只是卡住了

这是我的 Spring 启动 App_controller :

@RestController
@CrossOrigin(origins = "*")
public class App_Controller {

    int id = 0;
    ArrayList<Player> players = new ArrayList<Player>();
    public void addTab(Player p){
       players.add(p);
    }

    @MessageMapping("/batch-socket")
    @SendTo("/topic/messages")
    public String send(String message) throws Exception {
        String time = new SimpleDateFormat("HH:mm").format(new Date());
        return (message + " : " + time);
    }


    @RequestMapping (value = "/error", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public String error(){
        return "erreur";
    }
}

这是我的 corsConfiguration :

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry){
                registry.addMapping("/**")
                        .allowCredentials(true)
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .maxAge(3600);

            }
        };
    }
}

这是我的 WebSocketConfiguration :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/topic")
                .enableSimpleBroker("/app");
    }

    @Override public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/batch-socket");
        registry.addEndpoint("/batch-socket")
                .setAllowedOrigins("*")
                .withSockJS();
    }
}

最后,这是我连接到这个 WebSocket 的函数:

    function connect(){
        var socket = new SockJS("http://localhost:8080/batch-socket");
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame){
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/messages', function(msgOutput){
                console.log(msgOutput);
            })
        })

    }

我尝试只添加 @CrossOrigin(origins="*") 和 @CrossOrigins(origins="http://localhost:63342") 并使用我的 CorsConfig 测试多种可能性。

提前感谢您的帮助 (对不起我的英语)

【问题讨论】:

    标签: javascript spring-boot websocket stomp sockjs


    【解决方案1】:

    你没有说你的带有 JS 的 HTML 页面是如何加载的。它是相同的 localhost:8080 还是本地文件?
    对于测试,您可以告诉 Chrome 忽略 cors 限制:

    chrome --disable-web-security --user-data-dir={some dir}

    在你的代码中你做了两次registry.addEndpoint(),删除一个并将“*”替换为“http://localhost:63342”。删除所有其他 CORS 相关代码。

    【讨论】:

    • 我的 html 页面加载到其他端口,63342 正好和我的 Spring Boot 应用程序在 8080 端口上
    • 显示 curl -v http://localhost:8080/batch-socket 返回的内容
    • 显示这个:image
    • 天哪,谢谢它的工作,我不知道为什么在互联网上找到的例子不起作用,但非常感谢你
    【解决方案2】:

    我认为你不需要创建@bean WebMvcConfigurer corsConfigurer,如果它是为了一个简单的测试。你能做一个测试删除那个bean的注册并改变注释的顺序吗?

    @CrossOrigin(origins = "http://localhost:63342")
    @RestController
    

    【讨论】:

    • 我试过这个但没有改变,出现同样的错误这就像@CrossOrigins 没有被spring加载
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2021-09-09
    • 2021-08-14
    • 2016-05-04
    相关资源
    最近更新 更多