使用 DELETE 的 Access-Control-Allow-Origin 错误,同时使用 GET / POST 工作正常
Posted
技术标签:
【中文标题】使用 DELETE 的 Access-Control-Allow-Origin 错误,同时使用 GET / POST 工作正常【英文标题】:Access-Control-Allow-Origin error with DELETE, while working fine with GET / POST 【发布时间】:2019-01-20 14:49:56 【问题描述】:BackEnd 是 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】:你需要添加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
【讨论】:
以上是关于使用 DELETE 的 Access-Control-Allow-Origin 错误,同时使用 GET / POST 工作正常的主要内容,如果未能解决你的问题,请参考以下文章