springboot跨域配置

young 488 2021-10-17
@Configuration
public class CorsFilterConfiguration implements WebMvcConfigurer {
	@Bean
	public FilterRegistrationBean<CorsFilter> corsFilterBean() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		config.addAllowedOrigin("*");
		config.addAllowedHeader("*");
		config.addAllowedMethod("*");
		config.setMaxAge(3600L);
		source.registerCorsConfiguration("/**", config);
		FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
		// 这个顺序很重要哦,为避免麻烦请设置在最前
		bean.setOrder(0);
		return bean;
	}
}