• spring cors的三种方式


    @CrossOrigin 注解

    如果想要对某一接口配置 CORS,可以在方法上添加 @CrossOrigin 注解 :

    @CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String greetings() {
        return "{"project":"just a test"}";
    }
    

    如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:

    @CrossOrigin(origins = {"http://localhost:9000", "null"})
    @RestController
    @SpringBootApplication
    public class SpringBootCorsTestApplication {
        
    }
    

    全局配置类

    由于WebMvcConfigurerAdapter类被弃用,新的实现是:

    @Configuration
    public class WebMvcConfg implements WebMvcConfigurer {
      //省略
    }
    @Configuration
    public class WebMvcConfg extends WebMvcConfigurationSupport {
      //省略
    }
    

    所以配置类可以这样写:

    @Configuration
    public class WebMvcConfig  implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost.com")
                    .allowedMethods("GET", "POST")
                    .allowedHeaders()
                    .allowCredentials(true);
        }
    }
    

    也可以这样写:

    @Configuration
    public class WebMvcConfig {
        @Bean
        public WebMvcConfigurationSupport corsBeanConfigurer() {
            return new WebMvcConfigurationSupport() {
                @Override
                protected void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                            .allowedOrigins("http://localhost.com")
                            .allowedMethods("GET", "POST", "PUT", "DELETE")
                            .allowedHeaders()
                            .allowCredentials(true);
                }
            };
        }
    }
    

    过滤器

    过滤器添加头

    @Configuration
    public class MyConfiguration {
    
    	@Bean
    	public FilterRegistrationBean corsFilter() {
    		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    		CorsConfiguration config = new CorsConfiguration();
    		config.setAllowCredentials(true);
    		config.addAllowedOrigin("http://domain1.com");
    		config.addAllowedHeader("*");
    		config.addAllowedMethod("*");
    		source.registerCorsConfiguration("/**", config);
    		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    		bean.setOrder(0);
    		return bean;
    	}
    }
    
  • 相关阅读:
    input回车问题
    Jquery-无法有效获取当前窗口高度
    微信JSSDK支付接口-安卓机无法正常调起接口
    Kafka 1.1新功能:数据的路径间迁移
    KSQL和Flink SQL的比较
    关于Kafka监控方案的讨论
    关于Kafka配额的讨论(2)
    关于Kafka配额的讨论(1)
    【译】Flink + Kafka 0.11端到端精确一次处理语义的实现
    Kafka元数据缓存(metadata cache)
  • 原文地址:https://www.cnblogs.com/arrayblog/p/14196787.html
Copyright © 2020-2023  润新知