CORS problem when sending requests from frontend to backend

Discussão em 'Angular' iniciado por Kire Boshkovski, Fevereiro 22, 2025.

  1. This is the message I get in my console everytime I try to send api request to backend. I use spring boot with spring security.

    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.

    all error messages after trying to send a request

    I tried using @CrossOrigin()

    @RestController
    @AllArgsConstructor
    @CrossOrigin(origins = "http://localhost:4200")
    public class AuthController {
    private final UserService userService;
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestParam String username,
    @RequestParam String email,
    @RequestParam String password) {
    try {
    this.userService.registerUser(username, email, password);
    return ResponseEntity.ok("User registered successfully");
    } catch (Exception e) {
    System.err.println(e.getMessage());
    return ResponseEntity.badRequest().body(e.getMessage());
    }
    }
    }


    This is my configuration

    public class SpringSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http
    .cors(Customizer.withDefaults())
    .csrf(AbstractHttpConfigurer::disable)
    .authorizeHttpRequests((requests) -> requests
    .anyRequest().permitAll()
    );

    return http.build();
    }
    }

    Continue reading...

Compartilhe esta Página