目录
一、注解 @CrossOrigin 可以从controller层面解决单个controller跨域问题
二、服务中的 CorsFilter ,这个 spring webmvc 中给出过滤器层面的跨域
三、网关中的CorsWebFilter ,这个是spring webflux中的过滤器
四、通过 配置文件 进行跨域设置(微服务项目下推荐使用此方法)
一、注解 @CrossOrigin 可以从controller层面解决单个controller跨域问题
直接在需要跨域的Controller的类上添加 @CrossOrigin 跨域注解即可。
@CrossOrigin //在controller类上添加此注解
二、服务中的 CorsFilter ,这个 spring webmvc 中给出过滤器层面的跨域
当一个模块中controlller过多时,添加注解过于繁琐,可以创建一个配置类对象,进行跨域设置,'' FilterRegistrationBean<Corsfilter> ''。
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* FilterRegistrationBean<CorsFilter> 这个是web MVC中给出的过滤器
* 解决多个Controller中的跨域问题
*/
@Configuration
public class CorsFilterConfig {
@Bean
public FilterRegistrationBean<CorsFilter>
filterFilterRegistrationBean(){
UrlBasedCorsConfigurationSource configSource =
new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration =
new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.setAllowCredentials(true);
configSource.registerCorsConfiguration("/**",
corsConfiguration);
FilterRegistrationBean<CorsFilter> fBean =
new FilterRegistrationBean<>(
new CorsFilter(configSource));
fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return fBean;
}
}
三、网关中的CorsWebFilter ,这个是spring webflux中的过滤器
一个网关管理多个服务时,设置此配置类对象,可以从网关层面解决多个服务的跨域问题,这就不需要每个服务都写一遍跨域了。
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
/**
* CorsWebFilter这个是spring webflux中的过滤器
* 可以解决网关层面多个服务的跨域问题
*/
@Configuration
public class CorsFilterConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource configSource =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
configSource.registerCorsConfiguration("/**",config);
return new CorsWebFilter(configSource);
}
}
四、通过 配置文件 进行跨域设置(微服务项目下推荐使用此方法)
此方法在微服务项目下可以配置到nacos等配置中心, 未来项目发布后能更灵活的处理各种请求。
spring:
cloud:
gateway:
globalcors: #跨域配置
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods: "*"
allowCredentials: true