spring-boot - Spring Boot 通过 application.properties 启用 CORS

标签 spring-boot cors

我使用由您的实体类自动启动的 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/

相关文章:

java - 使用 Autowiring 时,抽象类对象的子类为 null

spring-boot - 引起原因:java.lang.NoSuchMethodError:org.apache.tomcat.util.res.StringManager.getManager(Ljava/lang/Class;)

http - 非 2xx 状态代码响应是否应包含 CORS 特定 header

angularjs - 允许 Nginx 上的 CORS 与 AngularJS HTTP GET 配合使用

javascript - OAuth2 访问源错误

java - spring boot 获取url参数的方法

performance - 将 spring boot 应用程序用作 unix 服务时如何调整 jvm

javascript - 对于 CORS 错误,我还需要在客户端(Angular js)进行配置吗?

java - 使用@Query和@Modifying的Spring数据JPA PSQLException

spring - 浏览器未连接到 Springboot Websocket (sockjs)