You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用Axios请求Spring Boot后端时遭遇CORS问题求助

从源地址'http://localhost:5173'访问'http://localhost:8080/api/submitForm'的XMLHttpRequest被CORS策略阻止:预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'头。

我已在Spring Boot后端配置了允许所有源和请求方法的CORS规则,但React前端发起请求时仍遇到上述错误,无法完成数据传输。

后端CORS配置类

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

前端请求代码

import axios from 'axios';

const baseURL = "http://localhost:8080/api";

const sendDataToBackend = (data) => {
    axios
      .post(`${baseURL}/submitForm`, data)
      .then((response) => {
        console.log("Data sent successfully", response.data);
        // Additional logic
      })
      .catch((error) => {
        console.error("Error sending data to the backend", error);
        // Error handling logic
      });
};

解决思路

  1. 修复凭证与通配符源的冲突
    当设置allowCredentials(true)时,allowedOrigins不能使用*,浏览器禁止这种组合。需指定具体前端源:

    registry.addMapping("/**")
            .allowedOrigins("http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
    
  2. 检查Spring Security拦截
    若项目使用Spring Security,它会优先处理请求,可能覆盖CORS配置。需在Security配置中启用CORS:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll();
        }
    
        @Bean
        public CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173"));
            configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            configuration.setAllowedHeaders(Arrays.asList("*"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }
    
  3. 确保OPTIONS请求被放行
    检查后端过滤器或拦截器是否拦截了OPTIONS预检请求,需确保这类请求能正常返回CORS响应头。

  4. 重启后端服务
    修改CORS配置后必须重启Spring Boot应用,否则旧配置仍会生效。

  5. 移除不必要的凭证配置
    若前端请求不需要携带Cookie等凭证,可删除allowCredentials(true),保留allowedOrigins("*")即可。

内容的提问来源于stack exchange,提问作者NewBie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:02:22