Configure CORS for Spring Cloud Gateway



我有一个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:

应用程序.yml

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

但它不起作用。我很感兴趣为什么我的案例中会出现这个错误?FE和BE在不同的主机上运行。

如何解决此问题?

我通过定义一个使用的新beanCorsConfigurationSource来配置它。例如:

@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;
}

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

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

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

此外,您是否通过--proxy-conf运行FE应用程序进行重定向?我不是一个精通FE的人,但不使用changeOrigin: true。如果你必须使用changeOrigin: true,它只适用于GET,而对于其他人,你可能必须这样做。

最新更新