Spring Cloud (6) | spring cloud zuul 跨域问题No 'Access-Control-Allow-Origin' header

时间:2022-08-28 16:01:59

在用spring cloud zuul做Filter的时候,访问微服务出现跨域问题,在网上找了很多办法:

zuul:
ignored-headers: Access-Control-Allow-Credentials, Access-Control-Allow-Origin

参照:https://github.com/spring-cloud/spring-cloud-netflix/issues/1250
这个,发现还是没解决问题,

方法1
于是在Filter里面改代码解决了问题:
CloudFilter.java

@Component
public class CloudFilter extends ZuulFilter {

@Override
public String filterType() {
return "pre";
}

@Override
public int filterOrder() {
return 0;
}

@Override
public boolean shouldFilter() {
return true;
}

@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();

HttpServletResponse response = ctx.getResponse();
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
}

}

方法2
在@EnableZuulProxy注解里的Class类加入下面这个Bean:
用到CorsFilter这个类,需要import org.springframework.web.filter.CorsFilter;

    @Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}

参照:https://*.com/questions/28670640/spring-cloud-zuul-proxy-is-producing-a-no-access-control-allow-origin-ajax-r

更多系列文章推荐:

  1. Spring Cloud (20) | Spring Cloud Bus 使用kafka消息总线、gitlab添加webhooks实现自动刷新配置
  2. Spring Cloud (19) | Eureka Server 高可用服务注册中心
  3. Spring Cloud (18) | 给Eureka Server加上安全验证
  4. Spring Cloud (15) | Spring Boot、HikariCP、Mybatis和MySQL 配置HikariCP数据库连接池
  5. Spring Cloud (14) | 微服务不能从git/github/gitlab中获取数据库信息 can’t load properties from git/github/gitlab
  6. Spring Cloud (12) | Spring Cloud Zuul网关调用微服务,request请求参数是application/json
  7. Spring Cloud (11) | healthcheck开启健康检查
  8. Spring Cloud (10) | Eureka 各项参数详解
  9. Spring Cloud (8) | 把Spring Boot项目改造成tomcat容器启动
  10. Spring Cloud (7) | Mongodb 微服务
  11. Spring Cloud (6) | spring cloud zuul 跨域问题No ‘Access-Control-Allow-Origin’ header
  12. Spring Cloud (5) | 配置中心 Config Server 配置git or github or gitlab
  13. Spring Cloud (3) | spring cloud bus 消息总线kafka应用
  14. Spring Cloud (1) | java.net.UnknownHostException: eureka-server