问题1:gateway跨域问题
解决方案1:配置application.yml文件
spring:
application:
name: '@project.artifactId@'
profiles:
active: dev
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
allowedHeaders: "*"
allowCredentials: true
解决方案2:手动配置corsFilter
@Configuration
public class GlobalCorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.setMaxAge(36000L);
return config;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
问题2:跨域后,访问微服务header里Access-Control-Allow-Origin等会重复
原因:因为gateway和微服务都开启了跨域配置,因此会重复
解决方案1,修改application.yml配置默认过滤 default-filters
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
allowedHeaders: "*"
allowCredentials: true
default-filters:
- DedupeResponseHeader=Vary Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_UNIQUE
- DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_FIRST
解决方案2,只开启gateway的跨域,把微服务里的跨域全部删除、禁用
这样就愉快的完美解决啦啦啦!
网友评论