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

Spring Boot服务CORS策略缺失Access-Control-Allow-Origin头,React前端跨域请求失败求助

解决Spring Boot + React的CORS同源策略问题

看起来你遇到的核心问题是Spring Security拦截了请求,导致你的CORS配置没有生效——从你的pom.xml可以看到,你已经引入了spring-boot-starter-security依赖,这个依赖会默认启用安全过滤链,它的执行优先级高于普通的CORS配置,所以即使你加了@CrossOrigin或者WebMvc的全局CORS配置,请求还没走到这些配置就被Security处理了,自然不会返回CORS响应头。

下面是针对你场景的可行解决方案:

1. 清理重复依赖

首先,你的pom.xml里重复添加了spring-boot-starter-security,先把其中一个删掉,避免依赖冲突:

<!-- 删掉重复的这个 -->
<!--<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>-->

2. 配置Spring Security支持CORS

创建(或修改)Spring Security的配置类,明确指定CORS配置,让Security在处理请求时先应用CORS规则:

package com.example.Blogging.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 启用CORS并指定配置源
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 临时关闭CSRF(如果你的React前端还没配置CSRF令牌,先关闭以便测试,后续可以按需开启)
                .csrf(csrf -> csrf.disable())
                // 测试阶段允许所有请求通过,后续可以根据需求配置权限规则
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
        
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 指定允许的前端源(不要用*,生产环境要明确指定)
        config.setAllowedOrigins(List.of("http://localhost:3000"));
        // 允许所有HTTP方法
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许所有请求头
        config.setAllowedHeaders(List.of("*"));
        // 允许携带凭证(比如Cookie)
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径应用CORS配置
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

3. 简化WebMvc的CORS配置(可选)

如果你之前的WebConfig用的是过时的WebMvcConfigurerAdapter,可以改成实现WebMvcConfigurer接口(Spring Boot 2.x推荐方式),不过有了上面的Security配置,这个WebMvc的配置可以保留也可以去掉,因为Security的CORS配置已经覆盖了全局:

package com.example.Blogging.config;

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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

4. 测试注意事项

  • 重启你的Spring Boot应用,确保新的配置生效
  • 用浏览器无痕模式测试,避免之前的缓存影响结果
  • 检查浏览器控制台的请求头,确认Access-Control-Allow-Origin是否已经出现在响应头中

这样配置后,你的React前端应该就能正常和Spring Boot后端通信了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:04:08