我使用由您的实体类自动启动的 Spring Boot API RESTful。我正在从前端 Web 应用程序使用这个 apiRest,但它给了我这个错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在使用指定的申请者.properties here 设置 CORS 配置.
我的基本配置是:
endpoints.cors.allow-credentials=true
endpoints.cors.allowed-origins=*
endpoints.cors.allowed-methods=*
endpoints.cors.allowed-headers=*
我在这些变量中尝试了不同的组合,但仍然无法正常工作。有任何想法吗?
最佳答案
这个在Spring官方文档中不是很清楚,很容易被Spring Boot官方文档误导linked here
真相是你不能使用 application.properties 文件设置全局 CORS 配置。您必须按照说明使用 JavaConfig here .
只需使用 @EnableWebMvc
@Configuration
上的注释扩展 WebMvcConfigurerAdapter
的类并覆盖 addCorsMappings
方法如下:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
关于spring-boot - Spring Boot 通过 application.properties 启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874351/