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);
        }
    }
  • 相关阅读:
    构造方法中使用this的含义
    Android Bundle类
    Android中使用PULL方式解析XML文件
    Android 创建与解析XML(四)—— Pull方式
    File的getPath()和getAbsolutePath()和getCanonicalPath()的区别
    Android-取出SDcard卡下指定后缀名的文件
    page、request、session和application有什么区别?
    prepareStatement的用法和解释
    pageContext对象的用法
    使用JSP连接MySql数据库读取HTML表单数据进行存贮
  • 原文地址:https://www.cnblogs.com/asker009/p/13612954.html
Copyright © 2011-2022 走看看