springcloud gateway 跨域问题
由于gateway使用的是webflux,而不是springmvc,所以需要先关闭webflux的cors,再从gateway的filter里边设置cors就行了。首先gateway版本<dependency><groupId>org.springframework.cloud</groupId><...
·
由于gateway使用的是webflux,而不是springmvc,所以需要先关闭webflux的cors,再从gateway的filter里边设置cors就行了。
首先gateway版本
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-core</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
** ps: 2.0.1.RELEASE 以下的版本有bug,Conten-Type 如果请求没有设置的话,会报空指针NPE 问题。
官方在2.0.1的版本修复了**
/**
* @ClassName CorsConfig
* @Author dlh
* @Date 2019/5/7 0007 下午 4:55
* @Version 1.0
**/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
网关之前设置的是全局filter
/**
* @ClassName CrossOriginFilter
* @Author dlh
* @Date 2019/5/7 0007 下午 4:50
* @Version 1.0
**/
@Component
public class CrossOriginFilter implements GlobalFilter, Ordered {
private static Logger logger = LoggerFactory.getLogger(CrossOriginFilter.class);
private static final String ALL = "*";
private static final String MAX_AGE = "18000L";
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {
ServerHttpRequest request = serverWebExchange.getRequest();
ServerHttpResponse response = serverWebExchange.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
return gatewayFilterChain.filter(serverWebExchange);
}
@Override
public int getOrder() {
return -300;
}
}
转载 https://www.jianshu.com/p/a46e62f9ad1c
更多推荐
已为社区贡献1条内容
所有评论(0)