最新Spring Boot 跨域配置,亲测好用

背景:

网上有很多跨域配置,但都存在各种各样问题;经过改良和测试后,最终形成一个稳定配置版本,我的Spring Boot版本是2.5.1

问题:

前后端分离后,进行联调,发现浏览器出报跨域问题

 

解决方案:

在config配置文件中添加下面代码类。这里很重要的一点是,在有其他拦截器的时候,通过bean.setOrder(0);设置加载顺序,我是通过这个方式解决问题的

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
// 是否允许发送Cookie信息
config.setAllowCredentials(Boolean.TRUE);
// 开放哪些Http方法,允许跨域访问
config.addAllowedMethod( " GET " );
config.addAllowedMethod( " PUT " );
config.addAllowedMethod( " POST " );
config.addAllowedMethod( " DELETE " );
config.addAllowedMethod( " OPTIONS " );
// 允许HTTP请求中的携带哪些Header信息
config.addAllowedHeader( " * " );
// 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
// config.addExposedHeader("*");
// 添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration( " /** " , config);

FilterRegistrationBean bean = new FilterRegistrationBean( new CorsFilter(configSource));
   //设置为第一
bean.setOrder( 0 );
return bean;
}
}

 

标签: Java

添加新评论