You need to enable JavaScript to run this app. Angular调用Spring Boot POST接口报CORS无Access-Control-Allow-Origin错误
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用Spring Boot POST接口报CORS无Access-Control-Allow-Origin错误

跨域报错根源定位

控制台报错翻译:从源http://localhost:4200发起的、访问http://localhost:8080/api/users/add的POST请求被CORS策略拦截:预检请求的响应未通过校验,目标资源不存在Access-Control-Allow-Origin响应头,请求直接失败。
触发原因明确:

  • 后端跨域配置失效
    • 接口上的@CrossOrigin注解配置的允许源为http://localhost:8080,和前端实际请求源http://localhost:4200完全不匹配
    • 单接口的@CrossOrigin逻辑在Controller层执行,而CORS预检OPTIONS请求会被Spring Security过滤器链提前拦截,根本无法到达Controller层,注解配置完全不生效
  • 前端配置方向错误
    • Access-Control-Allow-*系列字段是服务端返回给浏览器的响应头,前端在请求头中手动添加这些字段会被浏览器直接忽略,没有任何作用
  • Spring Security配置缺失跨域处理逻辑
    • 当前Security配置没有开启CORS支持,预检请求被直接拦截,无法返回跨域校验所需的响应头。
可直接落地的修复方案
  • 替换后端Security配置,新增全局CORS规则,修正后的配置段:

    @Override
    protected void configure(HttpSecurity http) throws Exception{
       http
         // 开启全局CORS支持,内置跨域规则无需额外编写自定义过滤器
         .cors(cors -> cors.configurationSource(request -> {
             CorsConfiguration config = new CorsConfiguration();
             // 匹配前端实际访问源
             config.setAllowedOrigins(List.of("http://localhost:4200"));
             // 显式放行OPTIONS预检请求
             config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
             config.setAllowedHeaders(List.of("*"));
             config.setAllowCredentials(true);
             // 预检结果缓存1小时,减少重复预检请求
             config.setMaxAge(3600L);
             return config;
         }))
         .csrf().disable()
         .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
        .addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig), JwtUsernameAndPasswordAuthenticationFilter.class)
        .authorizeRequests().antMatchers("/api/**").permitAll()
        .anyRequest().authenticated();
    }
    

    注意:删除Controller接口上配置错误的@CrossOrigin注解,避免规则冲突。

  • 修正前端代码,删除无效的CORS请求头配置,修正后的addUser方法:

    addUser(user: User): void {
      // 仅保留业务必需的请求头,CORS响应头由后端统一返回
      const HTTP_OPTIONS = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };
      const body = JSON.stringify(user);
      this.httpClient.post('http://localhost:8080/api/users/add', body, HTTP_OPTIONS).subscribe(
        (data: any) => {
          this.emitIntervenantsSubject(data);
          this.goToMainRoute();
        },
        (error) => {
          const message = 'server issue';
          this.emitErrorsSubject(message);
        }
      );
    }
    
  • 接口参数校验:确认提交的请求体所有字段(包括interfaceName、fname等)和后端User实体类映射、数据库表结构完全匹配,避免跨域校验通过后触发400参数解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 13:45:07