前言

列举出一种编码方式,(注意不是nginx的解决方案)是通过编码的方式告诉浏览器可以跨域访问了。

1. 在网关服务中添加Filter

@Component
public class MyCorsConfiguration {

    /**
     *
     * @return CorsWebFilter 为愧于的webfilter 有spring框架提供
     */
    @Bean
    public CorsWebFilter corsWebFilter(){

        /**
         * 返回一个CorsWebFilter ,构造其中需要传入连个形参,均为接口,可以直接new 接口
         * 是借口可以使用它的实现类来处理
         */
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        //构建CorsConfiguration
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedHeader("*");
        // 允许cookie跨域
        corsConfiguration.setAllowCredentials(true);

        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }

}


CorsWebFilter :是有spring提供的过滤器,会在请求到来之前和返回时经过这个过滤器,放入spring的容器中即可生效。

2. 在网关服务中添加Filter

跨域访问分两次

  1. 第一次options请求,此时请求到达gateway,网关在相应报文中告诉浏览器可以跨域:30d4de3ade9b439895d4b703cc741012~tplv-k3u1fbpfcp-jj-mark_3024_0_0_0_q75.jpg

  2. 浏览器发起真正的请求,则可以跨域,原理是跨域是浏览器的策略。
    85cd70247ebb40018820b0e500d2b395~tplv-k3u1fbpfcp-jj-mark_3024_0_0_0_q75.jpg
    这是通过编码的方式骗过浏览器的解决方案,在生产上使用nginx代理的方式解决。