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.