从他们documentation:
如果您使用的是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","PATCH");
}
};
}
}
Yuriy Yunikov的回答也是正确的.但我不喜欢“自定义”过滤器.
万一你有Spring Web Security导致麻烦.检查this SO答案.