Spring Boot+React项目CORS跨域阻塞问题求助
解决Spring Boot + React CORS阻塞问题
针对你的情况,按以下步骤排查和修复:
1. 修正配置类命名与扫描
你的配置类webConfig首字母小写,虽然Java语法允许,但Spring的组件扫描可能因约定(配置类首字母大写)漏扫。将类名改为WebConfig,确保Spring能识别并加载该配置:
@Configuration public class WebConfig implements WebMvcConfigurer { // 首字母大写 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }
注:exposedHeaders("Access-Control-Allow-Origin")无需手动设置,Spring会自动处理,可移除。
2. 检查Spring Security拦截(如果使用)
如果项目引入了Spring Security,默认的安全过滤器会优先于CORS配置生效,导致CORS规则被覆盖。需在Security配置中显式启用CORS:
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.CorsConfigurationSource; import java.util.Arrays; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 先启用CORS .csrf().disable() // 测试环境可临时关闭CSRF,上线后再配置 .authorizeRequests() .anyRequest().permitAll(); // 测试阶段允许所有请求,后续按需调整 } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("http://localhost:3000")); config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(Arrays.asList("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
3. 前端axios启用凭证传递
后端配置了allowCredentials=true,前端axios必须对应开启withCredentials,否则浏览器会拒绝接收响应:
const handleSubmit = async () => { try { const response = await axios.post('http://localhost:8080/api/Document', formData, { withCredentials: true // 新增此行 }); console.log('Form submitted successfully', response.data); } catch (error) { console.error('Error submitting form', error.response?.data || error.message); } };
4. 验证预检请求(OPTIONS)
浏览器发送POST前会先发OPTIONS预检请求,需确保后端能正确响应200状态码。可以用Postman直接请求OPTIONS http://localhost:8080/api/Document,检查响应头是否包含Access-Control-Allow-Origin: http://localhost:3000等CORS相关字段。
5. 清除浏览器缓存
强制刷新页面(Ctrl+Shift+R)或使用无痕模式测试,避免浏览器缓存旧的CORS策略导致问题。
内容的提问来源于stack exchange,提问作者Wiame
相关产品推荐
相关产品推荐

