Spring Boot Restful Service and CORS problem

Discussão em 'Angular' iniciado por canercin, Setembro 12, 2024.

  1. canercin

    canercin Guest

    I created a Restful service with Spring Boot and I am sending HTTP requests to this service with Angular. I was getting a CORS error when I sent a request with Angular and I used artificial intelligence to solve the error. In the first attempt, it asked me to suggested the following bean.

    @Bean
    public WebMvcConfigurer corsConfigurer(){
    return new WebMvcConfigurer() {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
    .allowedOrigins("http://localhost:4200")
    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
    .allowedHeaders("*")
    .allowCredentials(true);
    }
    };
    }


    Then, when I wanted to export the front-end as live server, I also got CORS error and it suggested me to add the following bean.

    @Bean
    public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("http://192.168.5.76:4200");
    config.addAllowedOrigin("http://localhost:4200");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
    }


    When I did some more research on the internet, I saw that the WebMvcConfigurer structure is recommended. But I don't understand which one I should use in which situation and I couldn't find a detailed explanation. I wonder if there is someone who can provide an explanatory source or explanation on this subject.

    Continue reading...

Compartilhe esta Página