跨域解决方案(Spring项目)

1.注入配置文件

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1允许任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        // 2允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

2.注解配置

@CrossOrigin(origins = "http://www.xxxx.com", maxAge = 3600)

也可直接将origins的value改为*

posted @ 2019-11-11 15:18  CHANGEMAX  阅读(753)  评论(0编辑  收藏  举报