【问题标题】:Getting CORS policy error while using spring boot with angular使用带角度的弹簧启动时出现 CORS 策略错误
【发布时间】:2019-07-14 18:11:54
【问题描述】:

我正在使用 Spring Boot 2.0.2,我的项目中有 spring-starter-web 和 spring-data-jpa,我暂时没有使用 Spring Security。 我创建了 RestControllers 并向它们添加了 @CrossOrigin 注释,并尝试使用此代码为我的 Angular 应用程序启用 CORS

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurer() {

        @Override
        public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")..allowedOrigins("*").allowedMethods("GET","POST","DELETE","PATCH","OPTIONS");
                }
            }
        };

}

但我的 Angular 应用程序仍然收到 CORS 错误

【问题讨论】:

    标签: java angular spring-boot spring-mvc cors


    【解决方案1】:

    试试这样的: 创建一个名为 CorsConfiguration 或任何名称的新类

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class CorsConfiguration implements WebMvcConfigurer {
    
    private static final String HTTP_LOCALHOST_4200 = "http://localhost:4200";
    private static final String GET = "GET";
    private static final String POST = "POST";
    private static final String PUT = "PUT";
    private static final String DELETE = "DELETE";
    private static final String HEAD = "HEAD";
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
        registry.addMapping("/**")
                .allowedOrigins(
                        HTTP_LOCALHOST_4200).allowedMethods(GET, POST, PUT, DELETE, 
    HEAD).allowCredentials(true);
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 2020-11-01
      • 2020-01-17
      • 1970-01-01
      • 2020-01-31
      • 2022-06-17
      • 2021-06-06
      • 2017-12-31
      相关资源
      最近更新 更多