这篇文章主要介绍了SpringCloud网关跨域配置代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Springboot版本:2.1.8.RELEASE
SpringCloud版本:Greenwich.SR2
yml配置:
春天: 云: 网关: globalcors: cors-configurations: “[/* *]”: #允许携带认证信息 #允许跨域的源(网站域名/ip),设置*为全部 #允许跨域请求里的头字段,设置*为全部 #允许跨域的方法,默认为获得和选择,设置*为全部 #跨域允许的有效期 allow-credentials:真 allowed-origins: ——“http://localhost: 13009” ——“http://localhost: 13010” allowed-headers:“*” allowed-methods: ——选项 ——得到 -职位 信息:3600 #允许响应头的信息 #默认仅允许如下6个: # cache - control #内容语言 #内容类型 #到期 # last - modified # Pragma # exposed-headers:
配置类:org.springframework.cloud.gateway.config.GlobalCorsProperties
网上有很多人说这样配无效,但我测试下来是可以的,如果真的无效,可以手动去装配横配置:
包com.longge.gateway.configuration; 进口org.springframework.beans.factory.annotation.Autowired; 进口org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 进口org.springframework.cloud.gateway.config.GlobalCorsProperties; 进口org.springframework.context.annotation.Bean; 进口org.springframework.context.annotation.Configuration; 进口org.springframework.web.cors.reactive.CorsWebFilter; 进口org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; 进口org.springframework.web.util.pattern.PathPatternParser;/* * * @author罗杰·杨 * @date 11/21/2019 */@ configuration @ConditionalOnBean (GlobalCorsProperties.class) 公开课CorsAutoConfiguration { @ autowired 私人GlobalCorsProperties GlobalCorsProperties; @ bean 公共CorsWebFilter corsFilter () { UrlBasedCorsConfigurationSource源=new UrlBasedCorsConfigurationSource(新PathPatternParser ()); globalCorsProperties.getCorsConfigurations () .forEach((路径,corsConfiguration)→源。registerCorsConfiguration(路径,corsConfiguration)); 返回新CorsWebFilter(源); } }
当然,我们更推荐在Nginx等中间件去做跨域的处理,业务服务就应该关注业务。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。