带有DELETE的Access-Control-Allow-Origin错误,同时使用GET / POST可以正常工作

时间:2018-08-13 19:54:30

标签: spring angular cors http-delete

后端是Spring,我已经像这样配置了CORS

@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("*");                
            }
        };
    }
}

现在我在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);
}

从Angular 6 FrontEnd中,我称这两个端点

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));
  }

第一个(和类似的GET方法)工作正常,当我尝试使用DELETE时,我得到了

  

无法加载http://localhost:8080/product/remove/2:响应   预检请求未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。因此,不允许原点“ http://localhost:4200”   访问。

1 个答案:

答案 0 :(得分:0)

您需要添加DELETE http-verb

对于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");
}
}

对于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");
        }
    };
}
}

要了解CORS如何与spring配合使用,请参考:

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

Spring security CORS Filter