首页 > 编程语言 > 详细

Springboot跨域和SpringCloud跨域

时间:2020-09-04 15:04:19      阅读:31      评论:0      收藏:0      [点我收藏+]

1、Springboot全局跨域

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

生成环境通常需要在配置文件里设置,而且origin一般不能用*号

application.yml文件配置

cors:
  allowed-origin: http://localhost,http://192.168.1.104

读取配置

@Data
@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsProperties {
    private String[] allowedOrigin = {"*"};
    private String[] allowedHeader = {"*"};
    private String[] allowedMethod = {"*"};
    private boolean allowCredentials = true;
}

注入CorsProperties 后获取

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(corsProperties.isAllowCredentials());
        for (String origin : corsProperties.getAllowedOrigin()) {
            config.addAllowedOrigin(origin);
        }
        for (String header : corsProperties.getAllowedHeader()) {
            config.addAllowedHeader(header);
        }
        for (String method : corsProperties.getAllowedMethod()) {
            config.addAllowedMethod(method);
        }
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

 

2、Springcloud跨域

微服务的跨域一般设置在网关(其他微服务的跨域必须去掉),配置与Springboot基本相同。

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration cfg = new CorsConfiguration();
        cfg.setAllowCredentials(true);
        cfg.addAllowedOrigin("*");
        cfg.addAllowedMethod("*");
        cfg.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", cfg);
        return new CorsWebFilter(source);
    }
}

 

Springboot跨域和SpringCloud跨域

原文:https://www.cnblogs.com/asker009/p/13612954.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!