SpringCloudGateway 多种方式跨域配置
现如今,互联网公司的架构基本上都是前后端分离的架构,当前端域名和后端暴露接口域名不完全一致时,前端就无法正常请求接口,这个时候,就需要后端支持跨域,而对跨域的支持,正常情况下都是在网关层面做支持,故在spring cloud gateway中支持跨域是很常见的场景。方式一spring:cloud:gateway:filter:remove-hop-by-hop:headers:# 以下是去掉网关默
·
现如今,互联网公司的架构基本上都是前后端分离的架构,当前端域名和后端暴露接口域名不完全一致时,前端就无法正常请求接口,这个时候,就需要后端支持跨域,而对跨域的支持,正常情况下都是在网关层面做支持,故在spring cloud gateway中支持跨域是很常见的场景。
方式一
spring:
cloud:
gateway:
filter:
remove-hop-by-hop:
headers:
# 以下是去掉网关默认去掉的请求响应头
- trailer
- te
- keep-alive
- transfer-encoding
- upgrade
- proxy-authenticate
- connection
- proxy-authorization
- x-application-context
# 以下是去掉服务层面定义的跨域
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-max-age
- vary
globalcors:
corsConfigurations:
'[/**]':
allowCredentials: true
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods: "*"
maxAge: 3628800
方式二
@Bean
public WebFilter corsFilter() {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (!CorsUtils.isCorsRequest(request)) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST,GET,OPTIONS,DELETE,PUT");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "content-type");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3628800");
return chain.filter(exchange);
};
}
方式三
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", buildConfig());
return new CorsWebFilter(source);
}
private CorsConfiguration buildConfig(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("content-type");
corsConfiguration.addAllowedMethod("POST,GET,OPTIONS,DELETE,PUT");
corsConfiguration.setMaxAge(3628800L);
return corsConfiguration;
}
}
更多推荐
已为社区贡献8条内容
所有评论(0)