报错信息提示为:“Failed to fetch. Possible CORS (Cross-Origin Resource Sharing) issues.” 这通常意味着前端在尝试从不同的源(域名、协议或端口)获取资源时遇到了跨源资源共享(CORS)的问题。
解释:
CORS是一种安全机制,防止非同源的域进行资源交互。当一个页面的JavaScript尝试请求另一个域的资源时,如果服务器没有明确允许,浏览器会阻止这种请求。
解决方法:
- 在Spring Cloud的后端服务中,可以通过添加一个过滤器来处理CORS预检请求,示例代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class CorsConfig {
 
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*") // 允许所有域,也可以指定特定域
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }
}- 如果你使用Spring Cloud Gateway作为API网关,可以在路由配置中添加相应的CORS全局配置:
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("cors", r -> r.path("/api/**")
                    .filters(f -> f.addResponseHeader("Access-Control-Allow-Origin", "*"))
                    .uri("http://backend-service"))
            .build();
}- 如果是使用Spring Security,确保CORS配置在Security配置之前。
- 对于Swagger的请求错误,确保Swagger UI能够正确加载,并且不是因为其他配置问题导致的错误。
确保在实施以上解决方案时,考虑安全风险,不要过度使用allowedOrigins("*"),因为这会使您的应用容易受到跨站点请求伪造(CSRF)攻击。