看項目代碼看到一個CORS跨域訪問配置類,特此瞭解下什麼是CORS跨域,以及Springboot 2.2.x版如何支持CORS跨域請求!!!
什麼是CORS
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing),是一種 AJAX 跨域請求資源的方式,支持現代瀏覽器,IE支持10以上。
詳見:什麼是CORS
Springboot開啓CORS跨域訪問支持
第一種方式:
@Configuration
public class CorsFilterConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
System.out.println(123456);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 可以設置部分地址可以進行訪問
List<String> origins = Arrays.asList("http://www.hjljy.cn", "http://api.hjljy.cn");
config.setAllowedOrigins(origins);
// 設置所有地址的請求都可以
config.addAllowedOrigin("*");
// 可以設置允許部分請求頭信息
// List<String> headers = Arrays.asList("Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers");
// config.setAllowedHeaders(headers);
// 設置爲允許所有請求頭信息
config.addAllowedHeader("*");
// 可以設置只支持部分請求方式
// List<String> methods = Arrays.asList("GET","POST","HEAD","OPTIONS","PUT");
// config.setAllowedMethods(methods);
// 設置爲支持所有請求方式
config.addAllowedMethod("*");
// 可以設置部分請求路徑纔可以進行訪問
// source.registerCorsConfiguration("/cors/**",config);
// 設置所有的請求路徑都可以訪問
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//設置優先級爲最高
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
第二種方式:
@Configuration
public class CorsFilterConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
System.out.println(123456);
registry.addMapping("/**").
allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*");
super.addCorsMappings(registry);
}
}