1. 使用场景
浏览器默认不允许跨域访问,包括我们平时ajax也是限制跨域访问的。
产生跨域访问的情况主要是因为请求的发起者与请求的接受者1、域名不同;2、端口号不同
2.代码实现
1 import org.springframework.context.annotation.Bean; 2 import org.springframework.context.annotation.Configuration; 3 import org.springframework.web.cors.CorsConfiguration; 4 import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 5 import org.springframework.web.filter.CorsFilter; 6 7 @Configuration 8 public class CorsConfig { 9 private CorsConfiguration buildConfig() { 10 CorsConfiguration corsConfiguration = new CorsConfiguration(); 11 corsConfiguration.addAllowedOrigin("*"); // 1 12 corsConfiguration.addAllowedHeader("*"); // 2 13 corsConfiguration.addAllowedMethod("*"); // 3 14 return corsConfiguration; 15 } 16 17 @Bean 18 public CorsFilter corsFilter() { 19 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 20 source.registerCorsConfiguration("/**", buildConfig()); // 4 21 return new CorsFilter(source); 22 } 23 }