React/Kotlin环境下CORS配置问题排查
解决React调用Spring Boot Kotlin API的CORS问题
问题描述
调用接口时触发CORS拦截错误:
Access to fetch at 'http://localhost:8080/api/v1/demo-controller/users' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. main.c454458801d49c3baba9.hot-update.js:31 GET http://localhost:8080/api/v1/demo-controller/users net::ERR_FAILED fetchUsers @ main.c454458801d49c3baba9.hot-update.js:31
问题根源
你的CORS配置方式有误:通过@Bean返回WebMvcConfigurer实现类的写法,Spring无法正确加载该配置。若项目集成了Spring Security,Security过滤器会优先于CORS过滤器执行,导致OPTIONS预检请求被拦截,无法返回合规的CORS响应头。
解决方案
方案1:无Spring Security场景的配置
创建配置类直接实现WebMvcConfigurer接口,无需通过@Bean注册:
@Configuration class WebConfig : WebMvcConfigurer { override fun addCorsMappings(registry: CorsRegistry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600) } }
方案2:结合Spring Security的配置
若项目使用Spring Security,必须在Security配置中显式启用CORS,同时配置CorsConfigurationSource:
@Configuration @EnableWebSecurity class SecurityConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http .cors() // 启用CORS支持 .and() // 以下为示例安全规则,可根据实际需求调整 .authorizeRequests() .antMatchers("/api/v1/demo-controller/users").authenticated() .and() .oauth2ResourceServer().jwt() } @Bean fun corsConfigurationSource(): CorsConfigurationSource { val corsConfig = CorsConfiguration() corsConfig.allowedOrigins = listOf("http://localhost:3000") corsConfig.allowedMethods = listOf("GET", "POST", "PUT", "DELETE", "OPTIONS") corsConfig.allowedHeaders = listOf("*") corsConfig.allowCredentials = true corsConfig.maxAge = 3600L val source = UrlBasedCorsConfigurationSource() source.registerCorsConfiguration("/**", corsConfig) return source } }
验证步骤
- 替换原有错误的CORS配置代码
- 重启Spring Boot后端服务
- 在React端重新发起请求,检查CORS错误是否消失
内容的提问来源于stack exchange,提问作者Daniel Fleck
相关产品推荐
相关产品推荐

