Frontend to backend communication issue: CORS error encountered

I’m having trouble with my web app. Every time I try to send an API request from my frontend to my backend, I get a CORS error in the console. Here’s what it says:

Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I’m using Spring Boot with Spring Security for my backend. I’ve tried adding @CrossOrigin(origins = "http://localhost:4200") to my controller, but it didn’t help. Here’s a simplified version of my controller:

@RestController
@AllArgsConstructor
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {
    private final AccountService accountService;

    @PostMapping("/signup")
    public ResponseEntity<String> signup(@RequestParam String username,
                                         @RequestParam String email,
                                         @RequestParam String password) {
        try {
            this.accountService.createAccount(username, email, password);
            return ResponseEntity.ok("Account created successfully");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

And here’s my security configuration:

public class WebSecuritySetup {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors(Customizer.withDefaults())
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests((requests) -> requests
                .anyRequest().permitAll()
            );
        return http.build();
    }
}

Any ideas on how to fix this CORS issue? I’m stuck and could really use some help.

yo dancingbutterfly, CORS can be a real pain! tried adding a global CORS config? something like this in ur WebSecuritySetup:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList(“http://localhost:4200”));
config.setAllowedMethods(Arrays.asList(““));
config.setAllowedHeaders(Arrays.asList(”
”));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, config);
return source;
}

hey, have u tried addin a CorsConfiguration bean? sometimes that fixes it. also, is ur frontend running on port 4200? what other fix attempts have u done? this CORS stuff, it’s so annoying sometimes, right?