后端是春天,我像这样配置了 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 前端,我调用了这两个端点
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:响应 预检请求未通过访问控制检查:否 "访问控制允许源"标头存在于请求的上 资源。因此不允许使用原产地"http://localhost:4200" 访问。
你需要添加 DELETE http-verb
对于春季网络 MVC
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
对于弹簧启动:
@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如何与弹簧一起工作,请参阅:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig
弹簧安全 CORS 过滤器