Hey everyone, I’m having trouble with CORS when trying to send API requests from my frontend to my backend. I’m using Spring Boot with Spring Security.
Every time I try to make a request, I get this error in my console:
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’ve tried adding @CrossOrigin(origins = "http://localhost:4200")
to my controller, but it’s not working. Here’s what my controller looks like:
@RestController
@AllArgsConstructor
@CrossOrigin(origins = "http://localhost:4200")
public class UserAuthController {
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) {
System.err.println(e.getMessage());
return ResponseEntity.badRequest().body(e.getMessage());
}
}
}
And here’s my security config:
public class WebSecuritySetup {
@Bean
public SecurityFilterChain filterChainConfig(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((requests) -> requests
.anyRequest().permitAll()
);
return http.build();
}
}
Any ideas on what I’m doing wrong or how to fix this CORS issue? Thanks in advance!