Spring cloud zuul 之跨域访问 您所在的位置:网站首页 zuul配置跨域 Spring cloud zuul 之跨域访问

Spring cloud zuul 之跨域访问

2024-07-10 02:25| 来源: 网络整理| 查看: 265

在构架微服务过程中,通过zuul作为网关,对业务服务进行路由。以往如果没有网关,服务api直接暴露给调用方,解决跨域访问的方式通常是在代码中进行如下定义:

@Configuration public class WebMvcConfig implements WebMvcConfigurer {

    // Comments this part due to cors exception happened when zuul is used, as cors is also set in      // zuul. This will cause duplicated setting of cors.     @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/**")             .allowedOrigins("*")             .allowCredentials(true)             .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")             .maxAge(3600);     }

这样对于单纯的服务调用来说是没有问题,但如果通过网关zuul路由后调用服务,会出现cors的异常报错。这是由于网关将请求进行重装后转发给服务api,同样存在跨域的问题,第一个想到的方案是在zuul中也加上跨域的代码:

@Component @Configuration public class GateWayCorsConfig {     @Bean     public CorsFilter corsFilter() {         final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();         final CorsConfiguration corsConfiguration = new CorsConfiguration();         corsConfiguration.setAllowCredentials(true);         corsConfiguration.addAllowedHeader("*");         corsConfiguration.addAllowedOrigin("*");         corsConfiguration.addAllowedMethod("*");         source.registerCorsConfiguration("/**", corsConfiguration);         return new CorsFilter(source);     } } 问题来了,zuul和服务都有了跨域的代码,当进行api调用时候,异常依旧出现,但类型变为:

搜寻各种文章,总结一下说法:

网关cors处理没有,服务cors处理没有,挂。

网关cors处理没有,服务cors处理有,挂。

网关cors处理有,服务cors处理有,挂。

网关cors处理有,服务cors处理没有,ok。

所以,删掉服务工程中的cors处理,算是解决此问题。

 

另外附加一下,在dubug时候网关会有连接超时的异常,将ribbon.ReadTimeout和ibbon.SocketTimeout值设为600000,发现不好用,把值改小一些为10000,有效果了,难道超时时长不能大于某个值吗,待以后探究。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有