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

Spring Boot + Angular配置后仍存在CORS跨域问题求助

解决Spring Boot 3.2.1与Angular 16的CORS跨域问题

环境信息

  • JDK: 17
  • Spring Boot: 3.2.1
  • Angular: 16
  • 系统: macOS Sonoma 14.2.1(Safari、Chrome浏览器)

当前配置代码

1. AdminController.java

@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "http://localhost:4200") // Through annotation
public class AdminController {

    @GetMapping
    public ResponseEntity<String> adminName(){
        return ResponseEntity.ok("admin");
    }

}

2. application.properties

cors:
  allowedOrigin: "http://localhost:4200"
  allowedHeaders: "*"
  allowedMethods: "POST, GET, OPTIONS, PUT, DELETE"
  allowedCredentials: false
  corsConfiguration: "/**"

3. SecurityConfig.java

@Configuration
public class SecurityConfig {

    @Value("${cors.allowedOrigin}")
    private String allowedOrigin;
    @Value("${cors.allowedHeaders}")
    private String allowedHeaders;
    @Value("${cors.allowedMethods}")
    private String allowedMethods;
    @Value("${cors.corsConfiguration}")
    private String corsConfiguration;

    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) { // global config
                registry.addMapping(corsConfiguration)
                        .allowedOrigins(allowedOrigin)
                        .allowCredentials(false)
                        .allowedHeaders(allowedHeaders)
                        .allowedMethods(allowedMethods);
            }
        };
    }

}

问题分析与解决方案

你的配置存在几个核心问题,逐一修正即可解决跨域问题:

1. 全局CORS配置未被Spring容器识别

当前SecurityConfig中的webMvcConfigurer方法缺少@Bean注解,Spring不会自动注册该配置类,导致全局CORS规则完全不生效。同时,allowedMethods传入的是逗号分隔字符串,需拆分为数组才能被正确识别:

@Configuration
public class SecurityConfig {

    @Value("${cors.allowedOrigin}")
    private String allowedOrigin;
    @Value("${cors.allowedHeaders}")
    private String allowedHeaders;
    @Value("${cors.allowedMethods}")
    private String allowedMethods;
    @Value("${cors.corsConfiguration}")
    private String corsConfiguration;

    @Bean // 添加注解让Spring注册该Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping(corsConfiguration)
                        .allowedOrigins(allowedOrigin)
                        .allowCredentials(false)
                        .allowedHeaders(allowedHeaders)
                        .allowedMethods(allowedMethods.split(", ")); // 拆分字符串为方法数组
            }
        };
    }

}

2. 移除控制器局部CORS注解

全局配置已经覆盖所有路径,控制器上的@CrossOrigin注解可能与全局规则冲突,直接删除即可:

@RestController
@RequestMapping("/admin")
public class AdminController {

    @GetMapping
    public ResponseEntity<String> adminName(){
        return ResponseEntity.ok("admin");
    }

}

3. 处理Spring Security的OPTIONS预检请求

如果项目引入了Spring Security,默认会拦截OPTIONS预检请求,需在安全配置中放行并启用CORS(Spring Boot 3.x推荐使用SecurityFilterChain):

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Value("${cors.allowedOrigin}")
    private String allowedOrigin;
    @Value("${cors.allowedHeaders}")
    private String allowedHeaders;
    @Value("${cors.allowedMethods}")
    private String allowedMethods;
    @Value("${cors.corsConfiguration}")
    private String corsConfiguration;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 启用CORS
                .csrf(csrf -> csrf.disable()) // 根据业务需求决定是否禁用CSRF
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行OPTIONS请求
                        .anyRequest().permitAll() // 调整为实际业务权限规则
                );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList(allowedOrigin));
        configuration.setAllowedHeaders(Collections.singletonList(allowedHeaders));
        configuration.setAllowedMethods(Arrays.asList(allowedMethods.split(", ")));
        configuration.setAllowCredentials(false);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(corsConfiguration, configuration);
        return source;
    }
}

4. 校验Angular请求配置

确保Angular请求未携带withCredentials(因为后端配置allowCredentials: false):

// Angular服务示例
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class AdminService {
  constructor(private http: HttpClient) {}

  getAdminName() {
    return this.http.get<string>('http://localhost:8080/admin');
    // 不要添加 { withCredentials: true }
  }
}

5. 清除浏览器缓存

浏览器可能缓存旧的CORS响应头,导致新配置不生效,可通过以下方式解决:

  • 强制刷新页面(Chrome/Safari按Cmd+Shift+R)
  • 使用无痕模式测试

总结

按上述步骤修正后,重启Spring Boot和Angular应用即可解决跨域问题。核心是确保全局CORS配置被Spring正确加载、Spring Security放行预检请求,避免局部与全局配置冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:32:32