最近在使用Gateway的一些踩坑跟填坑的過程
版本聲明
- Spring-Cloud:Hoxton.SR1
- Spring-boot:2.2.4.RELEASE
- Gateway:2.2.1RELEASE
因爲使用了較新的版本,之前支持的跨域方式不管用了/
因爲Gateway使用WebFlux,所以跨域設置需要開發者自己實現WebFluxConfigurer
在Gateway 2.1.3.RELEASE版本之前都可以使用以下代碼實現跨域
@Configuration
public class PreFlightCorsConfiguration {
@Bean
public CorsWebFilter corsFilter() {
return new CorsWebFilter(corsConfigurationSource());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.DELETE);
source.registerCorsConfiguration("/**", config);
return source;
}
}
配置文件也不需要更改。但是使用了新版本之後缺失效了。因爲作者已經封裝了一個DedupeResponseHeader過濾器。原帖
而且新的文檔也聲明這個過濾器 Gateway文檔
然後我修改了我原本的配置文件
server:
port: 8805
eureka:
instance:
prefer-ip-address: true
status-page-url: http://localhost:8805/swagger-ui.html#/
client:
serviceUrl:
defaultZone: http://localhost:8801/eureka/
# defaultZone: http://peer1:8801/eureka/
spring:
application:
name: Gateway-Server
cloud:
gateway:
# 跨域配置
# globalcors:
# corsConfigurations:
# '[/**]':
# allowedOrigins: "*"
# allowedMethods: "*"
# allowedHeaders: "*"
discovery:
locator:
lowerCaseServiceId: true
routes:
- id: Admin-Server
uri: lb://Admin-Server
predicates:
- Path=/admin/**
filters:
- StripPrefix=1
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
- id: Login-Server
uri: lb://Login-Server
predicates:
- Path=/login/**
filters:
- StripPrefix=1
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
#logging:
# level:
# org.springframework.cloud.gateway: debug
在轉發的微服務上添加這個
DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
添加完成后就能正常使用Put跟Delete請求了,跨域的問題也得到了解決