0

I am facing CORS problems in my Spring Boot project in combination with Angular.

I am using the following code and annotated it as configuration.

@Configuration
public class WebConfig {

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

In Angular I am adding this :

enter image description here

Unfortunately I am still getting this error:

enter image description here

None of them did the job.

Hilal Kaldane
  • 145
  • 1
  • 9
Gijs de Wert
  • 37
  • 1
  • 6
  • `CORS` needs to be managed server-side, so adding those headers client-side to your request won't have any affect. – goto Dec 23 '20 at 13:40
  • Try adding OPTIONS to the allowed methods – R. Richards Dec 23 '20 at 13:40
  • No, unfortunately not. – Gijs de Wert Dec 23 '20 at 14:13
  • 1
    [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied and offer poor usability. Instead, paste the code as text directly into your question. If you select it and click the `{}` button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code. – ChrisGPT was on strike Dec 24 '20 at 12:51

1 Answers1

-1

This is actually not your application's issue, but your browser's issue. Browsers make an OPTIONS request to application before sending actual data, to verify wheter they have access to make particular request or not.

To make it run what you can do is add OPTIONS into your code

@Configuration
public class WebConfig {

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

or use extensions such as CORS tools etc.

Hilal Kaldane
  • 145
  • 1
  • 9