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

SpringBoot 3 + Angular 16 CORS跨域问题:POST请求失败求助

问题:Spring Boot 3 + Angular 16 跨域请求失败(仅GET简单请求有效)

我试过网上能找到的所有解决方法,都没用。当前使用Spring Boot 3和Angular 16,奇怪的是返回字符串的简单GET请求可以正常工作,但POST登录请求触发跨域错误。

控制台错误:从源 'http://localhost:4200' 访问 'http://localhost:8080/api/v1/signin' 的XMLHttpRequest被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

后端CORS配置代码

@Configuration
public class WebConfig {
//    @Bean
//    public WebMvcConfigurer corsConfig() {
//        return new WebMvcConfigurer() {
//            @Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/api/v1/**")
//                        .allowedOrigins("http://localhost:4200")  
//                        .allowedMethods("*")
//                        .allowedHeaders("*") 
//                        .allowCredentials(true);
//            }
//        };
//    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

如上所述,我已经尝试过这些配置,只有简单GET请求有效,后端通过Postman测试完全正常。

前端登录请求代码

private apiUrl = 'http://localhost:8080/api/v1'

private headers
constructor(private httpClient: HttpClient, private userService: UserService) {

    this.headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Access-Control-Allow-Origin', '*')
      
}

login(email: string, password: string): Observable<any> {
    return this.httpClient.post<LoginResponse>(
      `${this.apiUrl}/signin`,
      {
        email: email,
        password: password
      },
      { observe: 'response' }
    ).pipe(
      map((response: HttpResponse<LoginResponse>) => {
        const token = response.body?.token;
        console.log('Token:', token);
        return response;
      })
    );
}

我反复检查过URL、数据类型以及登录表单返回的变量,这不是我第一次使用Spring和Angular,但之前一直用Spring Boot 2。我觉得问题可能出在不太熟悉的SecurityConfig类上:

SecurityConfig配置代码

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig  {
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userService.userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder);
        return authProvider;
    }
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf
                        .disable()
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(HttpMethod.POST, "/api/v1/signup", "/api/v1/signin", "/api/v1/bizsignin","/api/v1/bizsignup").permitAll()
                        .requestMatchers(HttpMethod.GET, "/api/v1/test/**","/api/v1/greetings").permitAll()
                        .anyRequest().authenticated()
                )
                .authenticationProvider(authenticationProvider()).addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}

附成功(GET)与失败(POST)请求的截图(原链接已移除)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:41:04