zoukankan      html  css  js  c++  java
  • Springboot跨域和SpringCloud跨域

    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);
        }
    }
  • 相关阅读:
    Java设计模式系列之策略模式
    设计模式系列之热身
    算术表达式系列之后缀表达式求值
    算术表达式系列之中缀表达式转后缀表达式
    Maven下使用Junit对Spring进行单元测试
    Windows命令行使用总结(持续更新)
    Eclipse中web项目部署至Tomcat步骤
    MyBatis保存完整日期的解决方法
    Redis(一)源码安装
    【集成学习】sklearn中xgboost模块中plot_importance函数(绘图--特征重要性)
  • 原文地址:https://www.cnblogs.com/asker009/p/13612954.html
Copyright © 2011-2022 走看看