Spring Gateway跨域问题

2022-07-03 09:09:12

问题场景

Gateway如果是单纯的跨域问题其实很好解决,CSDN上面也有很多文章关于Gateway跨域的。我同样也是按照这些文章来解决跨域问题。但是一测试发现前端各种报错:

// 浏览器console报错1:
The'Access-Control-Allow-Origin' header contains multiple values'http://xxxxxx, http://xxxxxx', but only one is allowed.// 浏览器console报错2:
The'Access-Control-Allow-Origin' header contains multiple values"*, *", but only one is allowed.

问题原因

最后发现其实按照网上的教程来定义gateway跨域配置是没有问题的,而会出现以上报错的原因是因为我在没使用gateway之前,我在每个服务中都定义了一个跨域配置类,这就导致了服务自身配置了跨域,而gateway又配置了一次跨域,造成重复跨域,就导致了浏览器报The ‘Access-Control-Allow-Origin’ header contains multiple values的错误。所以只需把各个服务自身的跨域配置去掉,然后在gateway中按网上的教程正常配置跨域即可。

以下提供一个gateway的跨域配置类,里面有两种实现的方式供各位小伙伴参考:

importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.reactive.CorsWebFilter;importorg.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;@ConfigurationpublicclassGatewayCorsFilter{@BeanpublicCorsWebFiltercorsWebFilter(){UrlBasedCorsConfigurationSource source=newUrlBasedCorsConfigurationSource();CorsConfiguration corsConfiguration=newCorsConfiguration();// 1、配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);// 2、设置哪些路径需要跨域
        source.registerCorsConfiguration("/**",corsConfiguration);returnnewCorsWebFilter(source);}// 该方法是通过重写WebFilter中的filter方法实现的,但通过测试上面的方法更方便,所以改用上面的方法//    @Override//    public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {//        ServerHttpRequest request = ctx.getRequest();//        if (CorsUtils.isCorsRequest(request)) {//            ServerHttpResponse response = ctx.getResponse();//            HttpHeaders headers = response.getHeaders();//            headers.remove(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);//            headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "你的VUE前端地址");//            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");//            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type,Accept,Accept-Language,Content-Language");//            if (request.getMethod() == HttpMethod.OPTIONS) {//                response.setStatusCode(HttpStatus.OK);//                return Mono.empty();//            }//        }//        return chain.filter(ctx);//    }}
  • 作者:Hey_JC
  • 原文链接:https://blog.csdn.net/Hey_JC/article/details/124682268
    更新时间:2022-07-03 09:09:12