网关解决跨域问题,spring-cloud-gateway zuul


1.跨域:对于一个路径:http:ip:port 如果协议 ip 端口三者有一个不同就有可能产生跨域问题

基于spring-cloud-gateway网关的解决方案,因为该网关使用的是reactor模式的webflux,所以:

@Configuration
public class CommonConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        return new CorsWebFilter(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(ServerWebExchange serverWebExchange) {
                CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.setAllowCredentials(true);//是否放行cookied
                corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);//所有的请求头都允许
                corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);//所有的请求方法GET POST等都允许跨域
                corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL);//所有的访问来源都允许跨域
                return corsConfiguration;
            }
        });


    }
}

如果是基于zuul作为网关,或者其他基于servlet的服务:

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .maxAge(3600);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM