Springboot版本:2.1.8.RELEASE
SpringCloud版本:Greenwich.SR2
yml配置:
spring: cloud: gateway: globalcors: cors-configurations: '[/**]': # 允許攜帶認證信息 # 允許跨域的源(網站域名/ip),設置*為全部 # 允許跨域請求里的head字段,設置*為全部 # 允許跨域的method, 默認為GET和OPTIONS,設置*為全部 # 跨域允許的有效期 allow-credentials: true allowed-origins: - "http://localhost:13009" - "http://localhost:13010" allowed-headers: "*" allowed-methods: - OPTIONS - GET - POST max-age: 3600 # 允許response的head信息 # 默認僅允許如下6個: # Cache-Control # Content-Language # Content-Type # Expires # Last-Modified # Pragma #exposed-headers:
配置類:org.springframework.cloud.gateway.config.GlobalCorsProperties
網上有很多人說這樣配無效,但我測試下來是OK的,如果真的無效,可以手動去裝配Cros配置:
package com.longge.gateway.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.cloud.gateway.config.GlobalCorsProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; /** * @author roger yang * @date 11/21/2019 */ @Configuration @ConditionalOnBean(GlobalCorsProperties.class) public class CorsAutoConfiguration { @Autowired private GlobalCorsProperties globalCorsProperties; @Bean public CorsWebFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); globalCorsProperties.getCorsConfigurations().forEach((path,corsConfiguration)->source.registerCorsConfiguration(path, corsConfiguration)); return new CorsWebFilter(source); } }
當然,我們更推薦在Nginx等中間件去做跨域的處理,業務服務就應該關注業務。
Nginx配置跨域可以參考我的另外一篇Blog:https://www.cnblogs.com/yangzhilong/p/9230778.html