基于注解的方式
gateway依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
需要在网关服务中给容器注入一个Bean
@Configuration
public class CORSConfig {
/**
* 网关统一配置跨域
*/
@Bean
public CorsWebFilter corsConfig(){
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*"); //允许任意请求头
corsConfiguration.addAllowedMethod("*"); //允许任意方法
corsConfiguration.addAllowedOrigin("*"); //允许任意请求来源
corsConfiguration.setAllowCredentials(true); //允许携带cookie
//表示所有请求都需要跨域
corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(corsConfigurationSource);
}
}
基于配置文件方式
需要在application.properties中添加如下配置
spring.cloud.gateway.globalcors.cors-configurations.allowedOrigins=*
spring.cloud.gateway.globalcors.cors-configurations.allowedMethods=*
spring.cloud.gateway.globalcors.cors-configurations.allowedHeaders=*
注意:如果在网关中配置了跨域,就不要在其他的服务模块的controller上添加@CrossOrigin注解了