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

Spring Boot配置@CrossOrigin后仍因CORS策略阻止Angular请求如何解决

可能的原因

  • 接口本身报错/404:当后端接口不存在、抛出异常未捕获时,Spring返回的错误响应不会携带CORS头,浏览器会误判为跨域拦截
  • @CrossOrigin配置不全:默认配置未放开所有请求方法、请求头,若前端请求带自定义头或特殊请求方法会触发拦截
  • 集成了Spring Security未配置CORS支持:Spring Security会优先拦截请求,OPTIONS预检请求未放行的话会直接返回异常,不会走到Controller的@CrossOrigin逻辑
  • 前端baseURL配置错误:比如后端端口写错、协议写错(http/https不匹配)、路径多了前缀等

解决方案

1. 基础排查

先用Postman等工具直接调用后端接口,确认接口能正常返回数据,排除接口本身404、报错的问题。同时确认Angular代码里的baseURL是http://[后端IP]:[后端端口],比如后端默认跑在8080的话就是http://localhost:8080,协议、IP、端口要和后端启动的完全一致。

2. 补全@CrossOrigin配置

把Controller上的@CrossOrigin注解补全属性:

@CrossOrigin(origins = "http://localhost:4200", allowedMethods = "*", allowedHeaders = "*", allowCredentials = "true")

3. 集成Spring Security的额外配置

如果项目引入了Spring Security,需要在Security配置类中开启CORS支持、放行OPTIONS预检请求,也可以直接配置全局CORS规则就不用每个Controller加@CrossOrigin了:

import org.springframework.http.HttpMethod;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().and() // 开启CORS支持
            .csrf().disable() // 前后端分离项目关闭CSRF校验
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有预检请求
            // 下方保留你自己原有的权限校验规则
            .anyRequest().authenticated();
    }

    // 全局CORS配置,可替代Controller上的@CrossOrigin注解
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:45:05