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向上转型和向下转型
    LeetCode记录之9——Palindrome Number
    LeetCode记录之7——Reverse Integer
    JAVA数据结构--插入排序
    JAVA数据结构--选择排序
    JAVA数据结构--冒泡排序
    HTTP协议04-返回状态码
    HTTP协议03-http特点及请求方式
    HTTP协议02-请求和响应的报文构成
    HTTP笔记01-http相关的基础知识
  • 原文地址:https://www.cnblogs.com/asker009/p/13612954.html
Copyright © 2011-2022 走看看