-1

BackEnd is Spring, I'v configured CORS like this

@SpringBootApplication
public class App {
    public static void main(String args[]){
        SpringApplication.run(App.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");                
            }
        };
    }
}

Now I got following code in Controller

@PostMapping("/add")
public ProductDto addProduct(@Valid @RequestBody ProductDto productDto){        
    return productService.addProduct(productDto);
}

@RequestMapping(path="/remove/{id}", method=RequestMethod.DELETE)
@ResponseBody
public String removeProduct(@PathVariable Long id) {
    return productService.removeProduct(id);
}

And from Angular 6 FrontEnd I'm calling those 2 endpoints

let httpHeaders = new HttpHeaders({
  'Content-Type' : 'application/json',
}); 

let options = {
  headers: httpHeaders
}; 

  addProduct() {    
    const product = new Product();

    product.name = this.productNameValue;
    product.categoryName = this.categoryValue;
    product.kcal = this.caloriesValue;
    product.protein = this.proteinValue;
    product.fat = this.fatValue;
    product.carb = this.carbsValue;   

    this.http.post('http://localhost:8080/product/add', JSON.stringify(product), options).subscribe(data => this.populateProductTable());     
  }


  removeProduct(x: any) {    
    const url = 'http://localhost:8080/product/remove/' + x.id;    
    this.http.delete(url, options).subscribe(data => console.log(data));
  }

First one (and similar GET method) works fine, when I try to use DELETE, I got

Failed to load http://localhost:8080/product/remove/2: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

user9309329
  • 313
  • 3
  • 13

1 Answers1

0

You need to add DELETE http-verb

For Spring Web MVC

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}

For Spring Boot:

@Configuration
public class MyConfiguration {

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
        }
    };
}
}

To know how CORS works with spring, refer:

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig

Spring security CORS Filter

Ketan Yekale
  • 2,108
  • 3
  • 26
  • 33