【问题标题】:Angular to Spring Boot Micro services connectivity ErrorAngular 到 Spring Boot 微服务连接错误
【发布时间】:2018-09-17 20:28:34
【问题描述】:

我正在尝试从我的 Angular 应用程序连接到基于 Spring Boot 和 Spring Cloud 构建的后端微服务。 UI 通过 Zuul 调用微服务层,路由到相应的微服务

从浏览器控制台中的 Angular UI 连接到微服务时出现以下错误:

加载失败:https://microservice url - 预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Access-Control-Allow-Origin。

谁能解释一下这个错误指的是什么?

【问题讨论】:

  • 典型的 CORS 问题。谷歌它有很多关于这个话题。
  • 请参阅:dontpanic.42.nl/2015/04/cors-with-spring-mvc.html 并确保包含 OPTIONS 方法。
  • 您的 API 不允许跨域资源共享。您必须将请求域列入白名单,或使用 JSONP(仅在打算使用 GET 但也支持 JSONP 时才有效)

标签: angular spring-boot microservices netflix-zuul


【解决方案1】:

我有同样的问题,我实现了接口过滤器

然后允许 Access-Control-Allow-Headers 和 Access-Control-Expose-Headers 添加 CORS 问题

@Component
public class CORSFilter implements Filter{


 @Override
        public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");


            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
            response.setHeader("Access-Control-Expose-Headers", "Content-Type, Access-Control-Expose-Headers, Authorization, X-Requested-With");
            chain.doFilter(request, response);
            logger.info(request.getRemoteAddr());
        }

}

【讨论】:

  • 谢谢,添加上面的 CORS 过滤器对我有用,只需进行一些额外的更改。 1. 我们使用了一些作为 Access-Control-Request-Headers 一部分的自定义标头,在 Access-Control-Allow-Headers 中添加了相同的标头 2. 将 @Order(Ordered.HIGHEST_PRECEDENCE) 添加到 CORS 过滤器跨度>
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 2021-09-20
  • 2019-02-22
  • 2019-10-15
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多