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

Angular 5请求Spring后端出现403跨域错误求助

解决Angular 5向Spring后端POST请求的CORS跨域问题

看起来你遇到了典型的**跨域资源共享(CORS)**问题——浏览器的同源策略阻止了Angular应用(运行在http://localhost:4200)访问Spring后端(http://localhost:8181)的资源,因为后端没有返回必要的CORS响应头,导致预检OPTIONS请求被拒绝(403状态码)。

下面是几种针对性的解决方法,核心是在Spring后端配置CORS支持:

1. 局部Controller级别的CORS配置

如果只想给特定的接口或Controller开启跨域支持,可以直接在对应的类或方法上添加@CrossOrigin注解:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
// 允许来自Angular应用的跨域请求
@CrossOrigin(origins = "http://localhost:4200")
public class TestController {

    @PostMapping
    public ResponseEntity<?> createTest(@RequestBody TestRequestDto test) {
        // 你的业务逻辑处理
        return ResponseEntity.ok("Test created successfully");
    }
}

这个注解会自动为该Controller下的所有接口添加Access-Control-Allow-Origin等必要的CORS响应头。

2. 全局应用级别的CORS配置

如果需要给整个应用的所有接口开启跨域支持,可以创建一个全局的CORS配置类:

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 GlobalCorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 匹配所有路径
                .allowedOrigins("http://localhost:4200") // 允许的源(Angular地址)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true); // 如果需要携带Cookie或认证信息,开启这个选项
    }
}

3. 结合Spring Security的额外配置

如果你的Spring应用使用了Spring Security,它会默认拦截OPTIONS预检请求,所以需要在Security配置中额外放行OPTIONS请求:

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.http.HttpMethod;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors() // 启用上面配置的CORS规则
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS预检请求
            // 其他权限规则配置
            .anyRequest().authenticated();
    }
}

Angular端的小提示

另外,你的Angular请求代码可以简化一下——不用手动JSON.stringify请求体,HttpClient会自动将对象序列化为JSON并设置正确的Content-Type: application/json头:

createTest() {
  const body = { 
    description: 'grtogjoritjhio',
    // 补充其他需要的字段
  };

  this.http.post('http://localhost:8181/test', body)
    .subscribe({
      next: (response) => console.log('请求成功:', response),
      error: (err) => console.error('请求失败:', err)
    });
}

本质上,这个问题的核心是后端没有正确响应浏览器的预检请求,只要在Spring端配置好CORS规则,就能解决跨域访问被拒绝的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:54:00