Springboot 和 Angular Websocket 的 CORS 问题

a4f*_*7lu 5 spring websocket sockjs

我有两个服务来构建 Spring Boot 应用程序

但我总是遇到这样的 CORS 问题

Access to XMLHttpRequest at '.../websocket-cr/info?t=1581585481804' from origin'http://localhost:8080' 
has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin'
header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. 
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials.

Run Code Online (Sandbox Code Playgroud)

8082上的Springboot服务

    public void registerStompEndpoints(StompEndpointRegistry registry) {
       registry.addEndpoint("/websocketcr").
       setAllowedOrigins("http://localhost:8080").withSockJS();
    }
Run Code Online (Sandbox Code Playgroud)

8080 上的 Angular 服务

    var socket = new SockJS('http://localhost:8080/websocket-cr');
    //socket.withCredentials = true ;
    stompClient = Stomp.over(socket);
Run Code Online (Sandbox Code Playgroud)

我努力了

    setAllowedOrigins("http://localhost:8080").withSockJS();
    setAllowedOrigins("*").withSockJS();
Run Code Online (Sandbox Code Playgroud)

或者在 javascript 中使用CORS Anywhere

    var socket = new SockJS('http://cors-anywhere.herokuapp.com/http://localhost:8082/websocket-cr');
    socket.withCredentials = true ;
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么

我应该为我的后端服务器创建角度代理吗?

或者通过 setAllowedOrigins('host:port') 就可以了

小智 0

在 SpringBoot 服务的 Main 类中,注入以下 bean,它将起作用

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer () {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*")
                    .allowedOrigins("*");
        }
    };
}
Run Code Online (Sandbox Code Playgroud)