无法在 spring 启动数据剩余中启用 CORS

cant enable CORS in spring boot data rest

我需要在我的 spring 引导数据 rest api 中启用全局 CORS,以防止在我从浏览器调用 api 时出现以下错误: http://localhost:8090/posts?user-id=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost'因此不允许访问。'。

我可以在浏览器中键入 url 并收到该资源的正确获取响应,但我无法从网页中的 ajax 调用进行相同的调用。

我缺少什么想法?

我的代码和配置如下:

@SpringBootApplication
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableWebMvc
public class Application  {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);

}

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    };
}

@Bean
public CommandLineRunner demo(UserRepository userRepository, PostRepository postRepository,
                              CommentRepository commentRepository, EventRepository eventRepository, VenueRepository venueRepository) {
    return (args) -> {

        User user = new User("fsdsdfsd","sdsdsds","121212");
        userRepository.save(user);

        Venue venue = new Venue("dsaesrdfddgd","aerttyhyyty","yyyyyyyyyyyyyy");
        venueRepository.save(venue);

        Event event = new Event("dsaesrdfddgd","aerttyhyyty","yyyyyyyyyyyyyy",venue,user);
        eventRepository.save(event);

        Post post = new Post("some posts are funny. Some are not.",user, event);
        postRepository.save(post);

        Comment comment = new Comment("commmentntnrnejfnerfdgdfgdfdt", user, post);
        commentRepository.save(comment);
    };
}

}

@RepositoryRestResource
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {


Page<Post> readBydeletedIsFalseOrderByCreated(Pageable pageRequest);

@CrossOrigin
Post readByIdAndDeletedIsFalse(Long postId);

}

buildscript {
repositories {
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'project'
    version = '0.1.0'
}

war {
    baseName = 'project'
    version = '0.1.0'
}


repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-rest")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("com.h2database:h2")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

尝试在全局配置中添加:

registry.addMapping("/**").allowedOrigins("*");

所以在评论中讨论我发现的内容后,您可以在 addCorsMappings 方法

中尝试这个
registry.addMapping("/**").allowedOrigins("http://localhost:8090")
                          .allowedMethods("PUT", "DELETE", "GET", "POST");

添加这个 bean 很有帮助

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

有趣的是 spring 不允许使用以下 bean 在 spring 引导数据 rest 端点上支持 CORS。但是,它可以按预期与开发人员创建的其他自定义端点一起使用。

@Bean
public WebMvcConfigurer corsConfigurer() {

    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET");
        }
    };
}