【问题标题】:Configure CORS for Spring Cloud Gateway为 Spring Cloud Gateway 配置 CORS
【发布时间】:2022-01-04 02:42:40
【问题描述】:

我有一个在本地运行的 React 应用程序,并且 Spring Cloud Gateway 作为 BE 在远程 VPS 上运行。我收到此错误:

Access to XMLHttpRequest at 'http://11.1.1.5:8080/api/business_structure' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试在 Spring Cloud Gateway 中配置 CORS:

application.yml

spring:
  application:
    name: service
  cloud:
   gateway:
    globalcors:
     cors-configurations:
      '[/*]':
        allowedOrigins:
          - "*"
          - "http://localhost:3000"
        allowedMethods:
          - GET
          - POST

但它不起作用。我很感兴趣为什么在我的情况下会出现此错误? FE 和 BE 在不同的主机上运行。

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs spring spring-cloud spring-cloud-gateway


    【解决方案1】:

    我通过定义一个新的 bean CorsConfigurationSource 来配置它。例如:

      @Bean
      public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration apiCorsConfiguration = new CorsConfiguration();
        apiCorsConfiguration.setAllowCredentials(true);
        apiCorsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        apiCorsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        apiCorsConfiguration.setAllowedMethods(Collections.singletonList("*"));
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", apiCorsConfiguration);
        return source;
      }
    
    

    但我认为你的配置是错误的。你有'[/*]':,但它应该是'[/**]':

    【讨论】:

    【解决方案2】:

    可能缺少一个额外的 *。类似的东西

    spring:
      cloud:
        gateway:
          globalcors:
            corsConfigurations:
              '[/**]':
                allowedOrigins: "http://mywebsite.com"
                allowedHeaders: "*"
                allowedMethods:
                - GET
                - POST
                - PUT
    

    您是否还通过 --proxy-conf 运行您的 FE 应用程序来重定向?我不是精通FE,但不要使用changeOrigin: true。如果您必须使用changeOrigin: true,它只适用于 GET,而对于其他人,您可能需要执行类似this 的操作。

    【讨论】:

    • 我收到Access to XMLHttpRequest at 'http://1.1.1.1.:8080/api/merchants/onboarding/currencies' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    • 您知道其他解决方案吗?问题是我在本地 PC 上运行 FE React 应用程序,在单独的服务器上运行 Spring Cloud Gateway。 CORS 不应阻止它。
    • 快速更新:我仅在 POST 请求时收到此错误。 GET 请求工作正常。
    • 当我在运行我的 Angular 应用程序时使用 --proxy-conf 时,我只遇到过这种情况。你确定 package.json 脚本,那是它没有使用任何代理?
    • 是的,这是package.json文件的内容:pastebin.com/021R4emp
    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 2019-06-15
    • 2022-10-19
    • 2020-06-22
    • 1970-01-01
    • 2021-06-04
    • 2020-06-21
    • 2018-11-15
    相关资源
    最近更新 更多