Springboot 和 Angular Websocket 的 CORS 问题 [英] CORS problems with Springboot and Angular Websocket

查看:26
本文介绍了Springboot 和 Angular Websocket 的 CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two service to build a Spring Boot application

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

But I always got CORS problems like this

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.

8082 上的 Springboot 服务

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

8080 上的 Angular 服务

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

我试过了

    setAllowedOrigins("http://localhost:8080").withSockJS();
    setAllowedOrigins("*").withSockJS();

或在javascript中使用CORS Anywhere

or use CORS Anywhere in javascript

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

最好的方法是什么

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

should I make angular proxy to my backend server?

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

or it is ok by setAllowedOrigins('host:port')

推荐答案

在你的 SpringBoot 服务的 Main 类中,注入下面的 bean,它会工作

In your Main class of the SpringBoot service , inject the below bean,it will work

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

这篇关于Springboot 和 Angular Websocket 的 CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆