SpringCloud gateway 跨域
时间: 2023-06-29 15:16:27 浏览: 136
spring cloud gateway请求跨域问题解决方案
要在Spring Cloud Gateway中实现跨域,可以通过添加一个自定义的GlobalFilter来实现。以下是一个简单的实现示例:
```java
@Component
public class CorsFilter implements GlobalFilter, Ordered {
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "3600";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (CorsUtils.isCorsRequest(request)) {
HttpHeaders headers = request.getHeaders();
ServerHttpResponse response = exchange.getResponse();
HttpMethod requestMethod = headers.getAccessControlRequestMethod();
HttpHeaders responseHeaders = response.getHeaders();
if (requestMethod != null) {
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOWED_ORIGIN);
responseHeaders.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS);
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
```
这个过滤器会检查请求是否为跨域请求,如果是,则添加必需的响应头以允许跨域请求。这里的ALLOWED_HEADERS、ALLOWED_METHODS、ALLOWED_ORIGIN、MAX_AGE和ALLOWED_ORIGIN都可以根据实际需要进行修改。最后,将这个过滤器添加到Spring Cloud Gateway的过滤器链中即可实现跨域。
阅读全文